xxxxxxxxxx
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
final _notifier = ValueNotifier<ThemeModel>(ThemeModel(ThemeMode.light));
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<ThemeModel>(
valueListenable: _notifier,
builder: (_, model, __) {
final mode = model.mode;
return MaterialApp(
theme: ThemeData.light(), // Provide light theme.
darkTheme: ThemeData.dark(), // Provide dark theme.
themeMode: mode, // Decides which theme to show.
home: Scaffold(
appBar: AppBar(title: Text('Light/Dark Theme')),
body: RaisedButton(
onPressed: () => _notifier.value = ThemeModel(mode == ThemeMode.light ? ThemeMode.dark : ThemeMode.light),
child: Text('Toggle Theme'),
),
),
);
},
);
}
}
class ThemeModel with ChangeNotifier {
final ThemeMode _mode;
ThemeMode get mode => _mode;
ThemeModel(this._mode);
}
xxxxxxxxxx
import 'package:flutter/material.dart';
void main() {
runApp(
MyApp(),
);
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool _isDarkMode = false;
String my_text = "Click the button below to toggle dark mode";
Icon my_icon = Icon(Icons.light_mode);
void _toggleDarkMode() {
setState(() {
_isDarkMode = !_isDarkMode;
if (_isDarkMode == false) {
my_text = "Click the button below to toggle dark mode";
my_icon = Icon(Icons.light_mode);
} else {
my_text = "Click the button below to toggle light mode";
my_icon = Icon(Icons.dark_mode);
}
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: _isDarkMode ? ThemeData.dark() : ThemeData.light(),
home: Scaffold(
appBar: AppBar(
title: Text('Dark Mode Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(my_icon.icon),
Text(my_text),
ElevatedButton(
onPressed: _toggleDarkMode,
child: Text('Toggle Dark Mode'),
),
],
),
),
),
);
}
}