• flutter 主题切换


    ### 主题
    ```
    // 1.main主文件
    import 'package:flutter_smart_park/config/theme.dart' show AppTheme; 
    
    Provide.value<ConfigModel>(context).$getTheme();
    
    Provide<ConfigModel>(
      builder: (context, child, configModel) {
        return MaterialApp(
          title: '智慧xx区',
          debugShowCheckedModeBanner: false,
          onGenerateRoute: Routes.router.generator,
          theme: AppTheme.getThemeData(configModel.theme),
          home: WillPopScope(
            onWillPop: () async {
              timerCountDown = TimerUtil(mInterval: 1000, mTotalTime: 1 * 1000);
              timerCountDown.setOnTimerTickCallback((int value) {
                if (value == 0) {
                  AndroidBackTop.cancelBackDeskTop();
                }
              });
              timerCountDown.startCountDown();
              AndroidBackTop.backDeskTop();
              return false;
            },
            child: Pages(),
          ),
        );
      },
    );
    // 2.theme 主题文件
    import 'package:flutter/material.dart';
    
    Map materialColor = {
      'purple': {
        "primaryColor": 0xFF7B1FA2,
        "primaryColorLight": 0xFF9C27B0,
      },
      'pink':{
        "primaryColor": 0xFFc2185b,
        "primaryColorLight": 0xFFd81b60,
      },
      'deeppink':{
         "primaryColor": 0xFFf50057,
        "primaryColorLight": 0xFFe91e63,
      },
      'blue':{
        "primaryColor": 0xFF1976D2,
        "primaryColorLight": 0xFF2196F3,
      },
    };
    
    class AppTheme {
      static Map mainColor = materialColor['purple'];
      static getThemeData(String theme) {
        mainColor = materialColor[theme];
        ThemeData themData = ThemeData(
          // scaffoldBackgroundColor: Colors.red, // 页面的背景颜色
    
          primaryColor: Color(mainColor["primaryColor"]), // 主颜色
          primaryColorLight: Color(mainColor["primaryColorLight"]),
          // 按钮颜色
          buttonTheme: ButtonThemeData(
            textTheme: ButtonTextTheme.primary,
            buttonColor: Color(mainColor["primaryColor"]),
          ),
    
          // appbar样式
          appBarTheme: AppBarTheme(
            iconTheme: IconThemeData(color: Colors.white),
            textTheme: TextTheme(
              title: TextStyle(
                color: Colors.white,
                fontSize: 20.0,
              ),
            ),
          ),
    
          // 图标样式
          iconTheme: IconThemeData(
            color: Color(mainColor["primaryColor"]),
          ),
        );
        return themData;
      }
    }
    
    // 3.provide 状态管理文件
    import 'package:flutter_smart_park/untils/local_storage.dart';
    class ConfigInfo {
      String theme = 'purple';   // 默认主题颜色
    }
    
    class ConfigModel extends ConfigInfo with ChangeNotifier {  // 将主题颜色保存至本地存储,持久化
      Future $getTheme() async {
        String _theme = await LocalStorage.get('theme');
        if (_theme != null) {
          $setTheme(_theme);
        }
      }
    
      Future $setTheme(payload) async {
        theme = payload;
        LocalStorage.set('theme', payload);
        notifyListeners();
      }
    }
    //  4.local_storage文件
    import 'dart:convert';
    import 'package:shared_preferences/shared_preferences.dart';
    
    class LocalStorage {
      static Future get(String key) async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        return prefs.getString(key);
      }
    
      static Future set(String key, String value) async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.setString(key, value);
      }
    
      static Future setJSON(String key, value) async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        value = json.encode(value);
        prefs.setString(key, value);
      }
    
      static Future remove(String key) async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.remove(key);
      }
    }
    
    // 使用
    Theme.of(context).primaryColor,
    
    ```
    
    
    
    
    
    
    ```
    (new) ThemeData({Brightness brightness, MaterialColor primarySwatch, Color primaryColor, Brightness primaryColorBrightness, Color primaryColorLight, Color primaryColorDark, Color accentColor, Brightness accentColorBrightness, Color canvasColor, Color scaffoldBackgroundColor, Color bottomAppBarColor, Color cardColor, Color dividerColor, Color highlightColor, Color splashColor, InteractiveInkFeatureFactory splashFactory, Color selectedRowColor, Color unselectedWidgetColor, Color disabledColor, Color buttonColor, ButtonThemeData buttonTheme, Color secondaryHeaderColor, Color textSelectionColor, Color cursorColor, Color textSelectionHandleColor, Color backgroundColor, Color dialogBackgroundColor, Color indicatorColor, Color hintColor, Color errorColor, Color toggleableActiveColor, String fontFamily, TextTheme textTheme, TextTheme primaryTextTheme, TextTheme accentTextTheme, InputDecorationTheme inputDecorationTheme, IconThemeData iconTheme, IconThemeData primaryIconTheme, IconThemeData accentIconTheme, SliderThemeData sliderTheme, TabBarTheme tabBarTheme, CardTheme cardTheme, ChipThemeData chipTheme, TargetPlatform platform, MaterialTapTargetSize materialTapTargetSize, PageTransitionsTheme pageTransitionsTheme, AppBarTheme appBarTheme, BottomAppBarTheme bottomAppBarTheme, ColorScheme colorScheme, DialogTheme dialogTheme, Typography typography, CupertinoThemeData cupertinoOverrideTheme}) → ThemeData
    package:flutter
    
    Create a [ThemeData] given a set of preferred values.
    
    Default values will be derived for arguments that are omitted.
    
    The most useful values to give are, in order of importance:
    
    The desired theme [brightness].
    
    The primary color palette (the [primarySwatch]), chosen from one of the swatches defined by the material design spec. This should be one of the maps from the [Colors] class that do not have "accent" in their name.
    
    The [accentColor], sometimes called the secondary color, and, if the accent color is specified, its brightness ([accentColorBrightness]), so that the right contrasting text color will be used over the accent color.
    
    See https://material.io/design/color/ for more discussion on how to pick the right colors.
    
    
    ```
    
    
    ```
    (new) ButtonThemeData({ButtonTextTheme textTheme: ButtonTextTheme.normal, double minWidth: 88.0, double height: 36.0, EdgeInsetsGeometry padding, ShapeBorder shape, ButtonBarLayoutBehavior layoutBehavior: ButtonBarLayoutBehavior.padded, bool alignedDropdown: false, Color buttonColor, Color disabledColor, Color highlightColor, Color splashColor, ColorScheme colorScheme, MaterialTapTargetSize materialTapTargetSize}) → ButtonThemeData
    package:flutter
    
    Create a button theme object that can be used with [ButtonTheme] or [ThemeData].
    
    The [textTheme], [minWidth], [height], [alignedDropDown], and [layoutBehavior] parameters must not be null. The [minWidth] and [height] parameters must greater than or equal to zero.
    
    The ButtonTheme's methods that have a [MaterialButton] parameter and have a name with a get prefix are used by [RaisedButton], [OutlineButton], and [FlatButton] to configure a [RawMaterialButton].
    
    
    ```
    

      

  • 相关阅读:
    Linux Network Related Drive
    Deformity ASP/ASPX Webshell、Webshell Hidden Learning
    PostgreSQL Reading Ad Writing Files、Execution System Instructions Vul
    Linux下修改进程名称
    karottc A Simple linux-virus Analysis、Linux Kernel <= 2.6.37
    python grammar、C/C++ Python Parsing Engine
    Java unserialize serialized Object(AnnotationInvocationHandler、ysoserial) In readObject() LeadTo InvokerTransformer(Evil MethodName/Args)
    Redis未授权访问漏洞分析
    Automated CMS category, version identification (CMS vulnerability detection)
    Linux process authority、the security risks in running process with high authority
  • 原文地址:https://www.cnblogs.com/john-hwd/p/10760376.html
Copyright © 2020-2023  润新知