📜  如何在颤动中快速添加暗模式 - 无论代码示例

📅  最后修改于: 2022-03-11 14:56:36.799000             🧑  作者: Mango

代码示例1
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  final _notifier = ValueNotifier(ThemeModel(ThemeMode.light));

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
      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);
}