Theming widgets
Learning objectives
- You know how to theme widgets.
It is also possible to provide themes to individual widgets without changing the theme of the whole application. Theming widgets is achieved using the Theme widget, which is given a ThemeData
object (property data
) and the widget to style (property child
).
In the following example, we have wrapped the ElevatedButton
widget with the Theme
widget, changing the color scheme into pink for the button. When you try out the application, you'll notice that the application still follows the normal styling, with the exception of the button.
The Theme
widget is actually used in the applications also more broadly. Giving the theme
property to MaterialApp
effectively leads to the whole application being wrapped with a Theme
widget.
Theme extensions
Custom themes are typically used to modify existing themes within Flutter, including e.g. overriding the primary color and adjusting used fonts. When building new widgets, widget styles are often also defined within the created widgets. If the styles for the new widgets are used in other new widgets as well, one possibility is to use the ThemeExtension to extract the theme to a separate location, and then relying on the extension in the new widgets.