【问题标题】:Flutter: Move theme (ThemeData) to a separate fileFlutter:将主题(ThemeData)移动到单独的文件中
【发布时间】:2022-01-05 09:24:11
【问题描述】:

我刚刚开始使用 Flutter 的一个新项目,而且对它完全陌生。

在 Flutter 中定义主题的惯例是什么?

我想要一个带有主题的单独文件,以保持main.dart 简单。有没有好的/正确/经典的方法来做到这一点?

目前我的main.dart 看起来像这样:

void main() => runApp(MaterialApp(
      initialRoute: '/',
      theme: ThemeData(
          appBarTheme: AppBarTheme(
            color: Colors.teal,
          ),
          textButtonTheme: TextButtonThemeData(
              style: TextButton.styleFrom(
            primary: Colors.teal,
          )),
          scaffoldBackgroundColor: Colors.grey[200],
          textTheme: TextTheme(
            bodyText1: TextStyle(),
            bodyText2: TextStyle(),
          ).apply(
            bodyColor: Colors.teal[800],
          )),
      routes: {
        '/': (context) => Loading(),
        '/home': (context) => Home(),
        '/alarms': (context) => SetUpAlarm(),
      },
    ));

【问题讨论】:

    标签: flutter dart styles themes


    【解决方案1】:

    您可以创建一个类并在其中定义主题,也可以在结尾使用逗号(,),这样您的代码将更加美化。

    class CommonMethod {
      
      ThemeData themedata = ThemeData(
          appBarTheme: AppBarTheme(
            color: Colors.teal,
          ),
          textButtonTheme: TextButtonThemeData(
              style: TextButton.styleFrom(
                primary: Colors.teal,
              ),
          ),
          scaffoldBackgroundColor: Colors.grey[200],
          textTheme: TextTheme(
            bodyText1: TextStyle(),
            bodyText2: TextStyle(),
          ).apply(
            bodyColor: Colors.teal[800],
          ));
    } 
    

    然后您可以通过 CommonMethod().themedata

    访问此主题

    【讨论】:

      【解决方案2】:
      For better practice to deal with Theme Structure in Flutter... You should create a separate file named e.g.  "app_themes.dart". And you can define your favorite colors in that file. It will be accessible in entire application. I'm sharing some code for your reference.
      
      
       static ThemeData darkTheme = ThemeData(
          brightness: Brightness.dark,
          backgroundColor: Colors.grey[700],
          accentColor: Colors.white,
        );
      
        static List<ThemeData> _appThemes = [
          ///Theme 1
          ThemeData(
              textSelectionHandleColor: Colors.white,
              selectedRowColor: Colors.green
      ),
         ///Theme 2
          ThemeData(
              textSelectionHandleColor: Colors.white,
              selectedRowColor: Colors.green
      ),
         ///Theme 3
          ThemeData(
              textSelectionHandleColor: Colors.white,
              selectedRowColor: Colors.green
      ),
      ]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-11-25
        • 1970-01-01
        • 1970-01-01
        • 2013-08-14
        • 2015-06-24
        • 2010-10-27
        • 1970-01-01
        相关资源
        最近更新 更多