Flutter:将主题(ThemeData)移动到单独的文件

Flutter: Move theme (ThemeData) to a separate file

我刚刚在 flutter 中开始一个新项目,对它完全陌生。

Flutter 中定义主题的约定是什么?

我想要一个带有主题的单独文件,以保持 main.dart 简单。有 good/correct/classic 的方法吗?

目前我的 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(),
      },
    ));

你可以自己创建一个class然后在里面定义主题也可以在末尾加上逗号(,)这样你的代码会更加美化。

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

访问此主题
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
),
]