1

I am (very) new to Flutter. I'm using Flutter 3 and Dart 2.17.

I am making a web app and am trying to set up the color scheme for my app. In CSS, I'd normally do something like this to define a set of colors for light and dark mode:

:root {
  --alpha: #FFF;
  --bravo: #F5F5F6;
}

@media (prefers-color-scheme: dark) {
  --alpha: #222630;
  --bravo: #171920;
}

I've read about Flutter's ThemeData, and as I understand it, it's a big list of styles so that if I were making an Android app, I'd have some sensible defaults for various pieces of the mobile UI. But since I am making a web app that has a fully custom UI, it feels like a lot of extra stuff I don't want.

What is a good way to define a bunch of color names and have them automatically switch their values when I switch between light and dark mode? Should I still use ThemeData? Or is there a simpler way when my UI is custom?

I'm hoping for something like this (this probably isn't valid Dart; I'm still learning):

//My view
Container(color: MyColors.alpha)

...and the values are read somewhere like this:

//Some other class
class MyColors {
  final alpha = darkMode ? const Color(0XFF222630) : const Color(0xFFFFFFFF);
  final bravo = darkMode ? const Color(0xFF171920) : const Color(0xFFF5F5F6);
}

Has anyone done something like this?

halfer
  • 19,824
  • 17
  • 99
  • 186
Clifton Labrum
  • 13,053
  • 9
  • 65
  • 128

1 Answers1

0

I'd suggest you use an @observable ThemeMode themeMode variable (read about the mobx state management here https://pub.dev/packages/mobx) to change the state of your whole widget tree starting from MaterialApp when the user changes the app theme, for example

themeMode: themeMode != null
                ? _controller.themeMode!
                : WidgetsBinding.instance.window.platformBrightness == Brightness.light
                    ? ThemeMode.light
                    : ThemeMode.dark,

and still use ThemeData to set which colors you want your components to use, like this

darkTheme: ThemeData(
                scaffoldBackgroundColor: MyColors.alphaDark,
                backgroundColor: MyColors.alphaDark,
                cardColor: MyColors.alphaDark,)
theme: ThemeData(
                scaffoldBackgroundColor: MyColors.bravoLight,
                backgroundColor: MyColors.bravoLight,
                cardColor: MyColors.bravoLight,)
class MyColors {
  final alphaDark = const Color(0XFF222630);
  final bravoLight = const Color(0xFFF5F5F6);
}
Container(color: Theme.of(context).cardColor)

And you can always create a custom ThemeData so you can call your components whatever you want

Matheus Melo
  • 172
  • 9