ximmyxiao
ximmyxiao

Reputation: 2811

Can I define dynamic color for dark&light mode in Flutter?

In iOS native development, I can define a dynamic color for using in both dark and light mode like this:

[UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull trait) {
    if (trait.userInterfaceStyle == UIUserInterfaceStyleDark) {
        return UIColorRGB(0x000000);
    } else {
        return UIColorRGB(0xFFFFFF);
    }
 }];

In Flutter, I know I can set these two colors into the MaterialApp's theme and darkTheme color property which will do the same thing. But the ThemeData's color property count is not infinite. And I don't think the color I want to create has something to do with the property name, like primaryColor or canvasColor and so on (in fact the color I want create may be used only once in the app).

So what is the best practice in Flutter to manage colors for light and dark mode?

Upvotes: 2

Views: 424

Answers (3)

Kokila
Kokila

Reputation: 317

You can define a separate method like this for getting light and dark themes.

class ColorUtil {
    static Color getColor(BuildContext context, Color lightColor, Color darkColor) {
    bool isLight = Theme.of(context).brightness == Brightness.light;
       if (isLight) {
             return lightColor;
          } else {
         return darkColor;
      }
  }
}
color: ColorUtil.getColor(context, Colors.black, Colors.white)

Upvotes: 0

ximmyxiao
ximmyxiao

Reputation: 2811

Add my own solution to one more option, anybody can reference Sucper's and my answer for your own condition

class AppColors {
  static Color L_F4F5F7_D_2B323D() {
    final Brightness brightness =
        WidgetsBinding.instance!.platformDispatcher.platformBrightness;
    return brightness == Brightness.light ? Color(0xFFF4F5F7) : Color(0xFF2B323D);
  }

  static Color L_FFF7E5_D_393730() {
    final Brightness brightness =
        WidgetsBinding.instance!.platformDispatcher.platformBrightness;
    return brightness == Brightness.light ? Color(0xFFFFF7E5) : Color(0xFF393730);
  }
}

Upvotes: 0

Sucper
Sucper

Reputation: 21

If I understood you correctly. You can check the current theme with

Theme.of(context).brightness == Brightness.dark

Theme.of(context).brightness == Brightness.dark
  ? return Color(0xFF2F6EA5)
  : return Colors.red;

Upvotes: 1

Related Questions