how to implement dark mode in flutter

后端 未结 6 2179
终归单人心
终归单人心 2021-02-05 09:05

I want to create a flutter app that has 2 light and dark mode themes that change by a switch in-app and the default theme is default android theme.
I need to pass some custo

6条回答
  •  渐次进展
    2021-02-05 09:10

    Screenshot:


    If you don't want to use any third party packages or plugins, you can use ValueListenableBuilder which comes out of the box with Flutter.

    Full code:

    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);
    }
    

提交回复
热议问题