Modularizing Themes
In this lesson, you'll learn how to organize themes to avoid duplicating the same styling code.
We'll cover the following
Modularizing themes
It’s a good idea to create a separate class for the Global theme created in the previous lesson to keep styling and design separate from the interface building codebase.
We can pull out the Global theme in a separate MyAppThemes
class, like below. Create a static
method appThemeLight()
to access the light theme from other interface classes. The static
keyword makes it accessible from other classes using MyAppThemes.appThemeLight()
.
class MyAppThemes {
static ThemeData appThemeLight() {
return ThemeData(
// Define the default brightness and colors for the overall app.
brightness: Brightness.light,
//appBar theme
appBarTheme: AppBarTheme(
//ApBar's color
color: Colors.white,
//Theme for AppBar's icons
iconTheme: IconThemeData(
color: Colors.black,
),
),
//Theme for app's icons
iconTheme: IconThemeData(
color: Colors.indigo.shade800,
),
);
}
}
The MaterialApp
can access the light theme by calling MyAppThemes.appThemeLight()
, like below:
MaterialApp(
debugShowCheckedModeBanner: false,
theme: MyAppThemes.appThemeLight(),
home: Scaffold(
//buildAppBarWidget() creates app bar widget
appBar: buildAppBarWidget(),
//buildBodyWidget() creates body for the app
body: buildBodyWidget(),
),
)
Keeping themes in a separate class makes it easier to switch themes very quickly. It’s as easy as calling a different method.
Get hands-on with 1400+ tech skills courses.