Add custom property to ThemeData in Flutter

2,796

Solution 1

Instead of adding custom property, we can extend ThemeData by extension function. For example, if we need a custom property for color, we can add extension function on ColorScheme. Color dependencies are now moved to Themedata.

// checking brightness to support dynamic themeing
extension CustomColorSchemeX on ColorScheme {
  Color get smallBoxColor1 =>
      brightness == Brightness.light ? Colors.blue : Colors.grey[400];
}

And then access that property through Theme.of(context)...

                        Container(
                          decoration: BoxDecoration(
                            border: Border.all(
                                color: Theme.of(context)
                                    .colorScheme
                                    .smallBoxColor1),
                        ),

Solution 2

Sadly, it appears that you simply can't - and the Flutter team doesn't seem to be interested in adding this, given their suggestion.

I think this is a major flaw, because we can't benefit from Theme.of(context) to automatically update all of our Widget that consume this ThemeData.

While some may say that you can use extensions to add new properties, you effectively won't know how to differ between multiple ThemeData (unless you can use some properties like Brightness, but I think this is just too hacky and not reliable to do so).

The alternative is to create another InheritedWidget (just like they said in the issue mentioned above) to handle your custom theme properties.

Share:
2,796
Newaj
Author by

Newaj

I am an android enthusiast, love to code in java.

Updated on December 21, 2022

Comments

  • Newaj
    Newaj over 1 year

    I need to change color of a widget based on theme. I have separate ThemeData for light and dark theme. Now is it possible to add a custom property to ThemeData so that I can change the color of the widget based on theme and using that custom property?