🍣

アプリのcolorをthemeで一括管理する

2023/05/17に公開

FlutterとDartのVersion
Flutter 3.7.7
Dart 2.19.4


primary swatch

swatch: 見本
指定されている型は、MaterialColor

Material Color

ベースとなる色と明暗の異なる10色をセットに定義したもの。

Colorsクラスで定義されてあるものは基本的にshade500をベースの色に設定しているみたい。


themeを設定しなかった場合

primarySwatch ??= Colors.blue;

上記のように、primarySwatchにmaterialColorであるColors.blueが定義され、あらゆる色がblueに設定される。

ColorSchemeプロパティ

[colorScheme] is the preferred way to configure colors. The other color
properties (as well as primaryColorBrightness, and primarySwatch)
will gradually be phased out

この文言を見る限り、現在は、colorSchemeをプロパティで設定するのが好ましいらしい。
実際、appbarのbackgroundの色を設定する場合、過去のFlutterバージョンでは、themedataのprimary colorで管理したようだが、私が使っているバージョンでは、primary colorを設定してもapp barのcolorは変更されなかった。

If null, then the [AppBarTheme.backgroundColor] is used. If that value is also null, then [AppBar] uses the overall theme's [ColorScheme.primary] if the overall theme's brightness is [Brightness.light], and [ColorScheme.surface] if the overall theme's [brightness] is [Brightness.dark].

ColorScheme の各プロパティの影響のある範囲について

主なwidgetの個々のthemeやapp内で指定していない場合に参照されるプロパティを記載 (* widget内で指定していない場合)

  • primary
    appbarのbackground
    textbuttonのforeground
    elevatedbuttonのbackground
    textfieldのcursor color
    textfieldのフォーカス時のborder color
    textfieldのlabel color

  • onPrimary
    appbarのforeground
    elevatedbuttonのforeground

  • secondary
    FABのbackground

  • onSecondary
    FABのforeground

参考文献

https://api.flutter.dev/flutter/material/ColorScheme-class.html
https://zenn.dev/sugitlab/articles/bef3a05963680a#materialcolor-をちゃんと理解しよう
https://zenn.dev/gen_kk/articles/cc538ffa392922

Discussion