Search code examples
flutterdartstylesthemes

Flutter: Move theme (ThemeData) to a separate file


I am just starting a new project in flutter and am absolutely new to it.

What is the convention with defining themes in Flutter?

I would like to have a separate file with a theme to keep the main.dart simple. Is there a good/correct/classic way to do it?

Currently my main.dart looks like this:

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(),
      },
    ));

Solution

  • you can create one class and define the theme there also can use comma (,) at the ending so your code will beautify more.

    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],
          ));
    } 
    

    and then you can access this theme as CommonMethod().themedata