Is it possible “extend” ThemeData in Flutter

I recommend this approach, which is simple, works with hot reload and can be easily extended to support switching between dark and light themes.

First create your own analog to ThemeData, let’s call it AppThemeData:

class AppThemeData {
  final BorderRadius borderRadius = BorderRadius.circular(8);

  final Color colorYellow = Color(0xffffff00);
  final Color colorPrimary = Color(0xffabcdef);

  ThemeData get materialTheme {
    return ThemeData(
        primaryColor: colorPrimary
    );
  }
}

The materialTheme can be used whenever the standard ThemeData is needed.

Then create a widget called AppTheme, which provides an instance of AppThemeData using the provider package.

class AppTheme extends StatelessWidget {
  final Widget child;

  AppTheme({this.child});

  @override
  Widget build(BuildContext context) {
    final themeData = AppThemeData(context);
    return Provider.value(value: themeData, child: child);
  }
}

Finally, wrap the whole app with AppTheme. To access the theme you can call context.watch<AppThemeData>(). Or create this extension…

extension BuildContextExtension on BuildContext {
  AppThemeData get appTheme {
    return watch<AppThemeData>();
  }
}

… and use context.appTheme. I usually put final theme = context.appTheme; on the first line of the widget build method.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)