how to implement dark mode in flutter

后端 未结 6 2134
终归单人心
终归单人心 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:21

    Screenshot:


    You can use provider to set the theme. Here's full code:

    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return ChangeNotifierProvider(
          create: (_) => ThemeModel(),
          child: Consumer(
            builder: (_, model, __) {
              return MaterialApp(
                theme: ThemeData.light(), // Provide light theme.
                darkTheme: ThemeData.dark(), // Provide dark theme.
                themeMode: model.mode, // Decides which theme to show. 
                home: Scaffold(
                  appBar: AppBar(title: Text('Light/Dark Theme')),
                  body: RaisedButton(
                    onPressed: () => model.toggleMode(),
                    child: Text('Toggle Theme'),
                  ),
                ),
              );
            },
          ),
        );
      }
    }
    
    class ThemeModel with ChangeNotifier {
      ThemeMode _mode;
      ThemeMode get mode => _mode;
      ThemeModel({ThemeMode mode = ThemeMode.light}) : _mode = mode;
    
      void toggleMode() {
        _mode = _mode == ThemeMode.light ? ThemeMode.dark : ThemeMode.light;
        notifyListeners();
      }
    }
    

    Answering OP questions:

    • Current theme can be found using:

      bool isDarkMode = MediaQuery.of(context).platformBrightness == Brightness.dark;
      

      or

      bool isDarkMode = SchedulerBinding.instance.window.platformBrightness == Brightness.dark;
      
    • You can provide theme to your whole app using theme for default themes, darkTheme for Dark themes (if dark mode is enabled by the system or by you using themeMode)

    • You can make use of provider package as shown in the code above.

提交回复
热议问题