Darya
Darya

Reputation: 21

How to detect Windows system theme changes in a Flutter app?

I want to be able to dynamically change the theme of my Flutter application when the system theme (dark mode/light mode) changes in Windows, but I don't know how to track this event in Flutter.

On macOS, there are no issues: when I change the system theme on macOS, the didChangePlatformBrightness method is triggered in my Flutter application. However, for Windows, this does not work — the didChangePlatformBrightness method is not called when the system theme changes on Windows.

Can anyone suggest how to track the system theme change event on Windows in my Flutter app? I would appreciate any advice or code examples!

Upvotes: 1

Views: 44

Answers (1)

il_boga
il_boga

Reputation: 1513

Hello and welcome to StackOverflow!
I don't have time right now to make a quick project to test if it works, but have you tried using this method somewhere near the root widget of your software?

EDIT
Ok, I managed to squeeze a line of code in a project I made to answer another question here on SO, and it seems to work. I just changed main.dart this way, and it worked (on Windows, at least):

@override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(brightness: MediaQuery.maybePlatformBrightnessOf(context) ?? Brightness.light),
      home:[the rest of your app...]

Your app will probably will be a little more complex than this, but you should be able to get it working by simply changing your ThemeData's brightness argument.

EDIT 2
I noticed that, if you user ColorScheme.fromSeed, this might throw an error. In this case, the brightness argument must be passed to ColorScheme.fromSeed and not to ThemeData

Upvotes: 0

Related Questions