Nowadays, almost every application has a dark theme feature, for example, YouTube, WhatsApp, and Instagram. Some of them have a toggle button in their app to on/ off the dark theme and others check theme settings in the device and display the selected theme. So in this blog let’s check how to implement the dark theme in the flutter.
Step 2: Now create a class and define the dark theme and light theme using ThemeData.
To change text color, use the color scheme property of ThemData.
Dark theme add- colorScheme: ColorScheme.dark()
Light theme add- colorScheme: ColorScheme.light()
To change the app bar use the appBar theme. In the app bar theme, you can add background color, text color, style, and icon color.
For changing the background color use scaffoldBackgroundColor property and use colors according to your theme.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classThemeClass{
staticThemeData lightTheme=ThemeData(
scaffoldBackgroundColor:Colors.white,
colorScheme:ColorScheme.light(),
appBarTheme:AppBarTheme(
backgroundColor:Colors.blue,
)
);
staticThemeData darkTheme=ThemeData(
scaffoldBackgroundColor:Colors.black,
colorScheme:ColorScheme.dark(),
appBarTheme:AppBarTheme(
backgroundColor:Colors.black,
)
);
}
Step 3: Now use these themes in your MaterialApp and add themeMode.system in the themeMode property of MaterialApp widget to check the theme of the device.
1
2
3
4
5
6
7
8
returnMaterialApp(
title:'Flutter Theme Demo',
debugShowCheckedModeBanner:false,
themeMode:ThemeMode.system,
theme:ThemeClass.lightTheme,
darkTheme:ThemeClass.darkTheme,
home:MyHomePage(),
);
Step 4: While defining colors in your app use theme properties instead of static color.
Now run your app and change theme settings in your device and again open the app and here is your selected theme. You can also change your theme back to the light theme by doing the same.
Output:
Thanks for reading this article ❤
If I got something wrong, let me know in the comments. I would love to improve.
Specializes in iOS and Flutter development with expertise in Swift, Storyboards, MVVM and Auto Layout. Focused on improving app performance and managing Apple Developer Account effectively.
And if we don’t have context available, then what?
Like in the main function:
SystemUiOverlayStyle(
statusBarColor: Theme.of(context).appBarTheme.backgroundColor,
);
we don’t have context available here as parameter from main function
Hello,
The main function doesn’t have context. For changing your status bar color use SystemUOverlayStyle in the app bar or, you can use an AnnotatedRegion<SystemUiOverlayStyle> which is a widget and only has an effect on the widget that you wrap.
And if we don’t have context available, then what?
Like in the main function:
SystemUiOverlayStyle(
statusBarColor: Theme.of(context).appBarTheme.backgroundColor,
);
we don’t have context available here as parameter from main function