Differences of using ThemeExtension vs class with static theme

Issue

Flutter 3 is out and I’ve been experimenting a little.

I have used the ThemeExtension

yt ref: https://www.youtube.com/watch?v=8-szcYzFVao

api ref: https://api.flutter.dev/flutter/material/ThemeData/extensions.html

and its great. However I’m starting to realize and ask myself I could have done the same result if I created a class with static const as properties such as colors, textstyles or any related theming.

Can someone enlighten me if why I should use ThemeExtensions instead?

Static class way:


// Setup
class AppColors {
  static const primaryColor = Color(0xFFFFFF);
  static const secondaryColor = Color(0xFFFFFF);
}


// Use case inside build

return Container(
  child: Text('Hello world'),
  color: AppColors.primaryColor,
)


ThemeExtension Way


// Setup
class AppColors extends ThemeExtension<AppColors>{
  final Color primaryColor;
  final Color secondaryColor;

  AppColors(this.primaryColor, this.secondaryColor);

  // .
  // ..
  // ... some @overrides such as copyWith() and lerp()
}


// Use case inside build

final colors = Theme.of(context).extensions<AppColors>()!;

return Container(
  child: Text('Hello world'),
  color: colors.primaryColor,
)

As you can see here setting up for ThemeExtension is quite huge compared on using just the static classes for theme to achieve the same result.

Solution

I think you should use Theme and/or ThemeExtension because:

  • You can use Theme(and ThemeExtension) in order to get widgets reactive. If some value is changed(color, text style, etc…), it will notify all listeners and the build method of dependent widgets will be dispatched.

  • If you change the themeMode to dark/light, all application will react to update widgets that are using the theme.

  • You can get scoped theme, so if you need some widgets or screen to use a different theme from the entire application, it will be possible too.

  • You can share you ThemeData between multiple apps and his use will looks like very similar in all apps

  • Theme is a good choice to keep a consistent visual pattern

  • The child/children widgets just need to know the Theme, as a Single source of truth. If you need to change all screens button’s color of the entire app, you will be safe and happy to do that in a single place 🙂

  • You don’t need to use ThemeExtension to get all these mentioned benefits, but if you do, it will make simpler to keep a very good documented Design System as code.

Answered By – Emanuel Braz

Answer Checked By – Katrina (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *