Flutter: programmatically cause darkTheme to be used

Viewed 466

In Flutter, you can set a dark theme to be used, which will be used if certain contexts (e.g. Dark Mode is set on Android Q). Is there a recommended way to allow that to be overridden programmatically; e.g, in response to a user preference?

I guess this could be done at the very top level of the app:

MaterialApp(
    theme: ThemeData.light(),
    darkTheme: ThemeData.dark(),
    themeMode: fromSomeState,
)

However, I'd also like to be able switch on whether or not the app is in dark mode programmatically at various points in the app (e.g. for image selection):

MediaQuery.of(context).platformBrightness == Brightness.dark;

I could try and update the MediaQueryData to override platformBrightness as well, but that can only be done inside MaterialApp, which seems awkward.

Is there a better pattern for doing this kind of thing?

1 Answers

You can check out dynamic_theme

How to use

Just add Dynamic Theme as the parent of your MaterialApp

DynamicTheme(
  defaultBrightness: Brightness.light,
  data: (brightness) => new ThemeData(
    primarySwatch: Colors.indigo,
    brightness: brightness,
  ),
  themedWidgetBuilder: (context, theme) {
    return new MaterialApp(
        .......
    );
  }
)

Get the currentBrightness using

    DynamicTheme.of(context).brightness;

And Set it using

    DynamicTheme.of(context).setBrightness(Theme.of(context).brightness == Brightness.dark? Brightness.light: Brightness.dark);

You can read more about it or create your own, check this medium Post

Edited

You can check the current OS theme using

MediaQuery.of(context).platformBrightness;

And set the theme accordingly.

Related