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

Dia*_*ana 3 themes styles dart flutter

我刚刚在 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(),
      },
    ));
Run Code Online (Sandbox Code Playgroud)

Jay*_*iya 6

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

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],
      ));
} 
Run Code Online (Sandbox Code Playgroud)

然后您可以通过CommonMethod().themedata访问该主题