The Tahaan
The Tahaan

Reputation: 7664

Flutter: Getting notified of display-mode (Dark/normal) changes in a running app

I use a function that checks MediaQuery.of(context).platformBrightness to determine the platform dark-mode setting:

This is called from the didChangeAppLifecycleState() and during startup - and it mostly works, except that I find that I need to minimise and re-open the app for it to receive the updated display mode.

The MediaQuery platformBrightness value appears to not be updated when the app comes to the foreground, but if you just minimise and bring the app back to forground, it is correct. This is on the Pie emulator using SDK 29.0.2.

Is there a way to directly listen for notifications about platform dark mode?

Note: There are a number of reasons why I don't use the Flutter Theme engine - The app themes are more complex than what Flutter provides and the user is given a preference setting to override the dark mode / normal setting to force the app to go use dark mode or normal mode and even provide dark and normal mode to older versions of android. However when the user selects "Auto" for dark/normal display mode the app should follow the platform mode, and in fact should switch even if th user does not actually leave the app, such as by just pulling down the shade and setting dark mode on or off. For this I would need a way to listen to the events.

UPDATE: Futher testing shows the the MediaQuery is in fact updated, but that the value is still reflecting the old value when didChangeAppLifecycleState() is called.

For example the following works:

@override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(
    if (displayModePreferenceSetting == DISPLAY_MODE_AUTO) {
      Timer(Duration(milliseconds: 333), () {
        switchDisplayMode(DISPLAY_MODE_AUTO);
      });
    }
  }

Upvotes: 1

Views: 415

Answers (1)

The Tahaan
The Tahaan

Reputation: 7664

It's much simpler than I thought, though I had to find the answer by accident.

A State widget allows you to override a method didChangePlatformBrightness()

Example:

  @override
  void didChangePlatformBrightness() {
    if (MediaQuery.of(context).platformBrightness == Brightness.dark) {
      print('PROBED DISPLAY MODE: DARK');
      // DO DARK MAGIC HERE
    } else {
      print('PROBED DISPLAY MODE: NORMAL');
      // NORMAL MODE HERE
    }
  }

Upvotes: 1

Related Questions