美文网首页
Flutter 夜间模式

Flutter 夜间模式

作者: 精简明了 | 来源:发表于2020-12-17 17:26 被阅读0次
    import 'package:flutter/material.dart';
    import 'package:flutter/cupertino.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatefulWidget {
      @override
      _MyAppState createState() => _MyAppState();
    }
    
    class _MyAppState extends State<MyApp> {
      ThemeMode themeMode = ThemeMode.light;
    
      void updateThemeMode() {
        setState(() => themeMode = getThemeMode());
      }
    
      ThemeMode getThemeMode() {
        switch (themeMode) {
          case ThemeMode.light:
            return ThemeMode.dark;
          case ThemeMode.dark:
            return ThemeMode.light;
          default:
            // 跟随系统
            return ThemeMode.system;
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          // 确定应用程序将使用哪个主题(请实现自定义)
          themeMode: themeMode,
          theme: ThemeProvider().getTheme(),
          darkTheme: ThemeProvider().getTheme(isDark: true),
          home: Scaffold(
            appBar: AppBar(
              title: Text('app title'),
            ),
            floatingActionButton: FloatingActionButton(
              child: Text('theme'),
              onPressed: () => updateThemeMode(),
            ),
          ),
        );
      }
    }
    
    class ThemeProvider {
      static ThemeProvider _instance;
    
      ThemeProvider._internal();
    
      factory ThemeProvider() {
        if (_instance == null) {
          _instance = ThemeProvider._internal();
        }
        return _instance;
      }
    
      getTheme({bool isDark: false}) {
        // 更多配置看内部实现,不配则使用默认样式
        return ThemeData(
          appBarTheme: AppBarTheme(
            brightness: isDark ? Brightness.dark : Brightness.light,
          ),
          brightness: isDark ? Brightness.dark : Brightness.light,
          cupertinoOverrideTheme: CupertinoThemeData(
            brightness: isDark ? Brightness.dark : Brightness.light,
          ),
        );
      }
    }
    

    内部获取当前主题

    bool _isDark = Theme.of(context).brightness == Brightness.dark;
    

    相关文章

      网友评论

          本文标题:Flutter 夜间模式

          本文链接:https://www.haomeiwen.com/subject/ypizgktx.html