Themes - Flutter
Themes - Flutter
Note
This recipe uses Flutter's support for Material 3 and the google_fonts package. As of
the Flutter 3.16 release, Material 3 is Flutter's default theme.
You can define app-wide themes. You can extend a theme to change a theme style for one
component. Each theme defines the colors, type style, and other parameters applicable
for the type of Material component.
After you define a Theme , use it within your own widgets. Flutter's Material widgets use
your theme to set the background colors and font styles for app bars, buttons,
checkboxes, and more.
If you don't specify a theme in the constructor, Flutter creates a default theme for you.
dart
MaterialApp(
title: appName,
theme: ThemeData(
// Define the default brightness and colors.
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.purple,
// ···
brightness: Brightness.dark,
),
Most instances of ThemeData set values for the following two properties. These
properties affect the entire app.
To learn what colors, fonts, and other properties, you can define, check out the
ThemeData documentation.
Apply a theme
To apply your new theme, use the Theme.of(context) method when specifying a
widget's styling properties. These can include, but are not limited to, style and color .
The Theme.of(context) method looks up the widget tree and retrieves the nearest
Theme in the tree. If you have a standalone Theme , that's applied. If not, Flutter applies
the app's theme.
In the following example, the Container constructor uses this technique to set its color .
dart
Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
color: Theme.of(context).colorScheme.primary,
child: Text(
'Text with a background color',
// ···
style: Theme.of(context).textTheme.bodyMedium!.copyWith(
color: Theme.of(context).colorScheme.onPrimary,
),
),
),
Override a theme
To override the overall theme in part of an app, wrap that section of the app in a Theme
widget.
dart
Theme(
// Find and extend the parent theme using `copyWith`.
// To learn more, check out the section on `Theme.of`.
data: Theme.of(
context,
).copyWith(colorScheme: ColorScheme.fromSeed(seedColor: Colors.pink)),
child: const FloatingActionButton(onPressed: null, child: Icon(Icons.add)),
);
Except as otherwise noted, this site is licensed under a Creative Commons Attribution 4.0 International
License, and code samples are licensed under the 3-Clause BSD License.