ぽぴなび

知って感動した技術情報・生活情報や買ってよかったものの雑記です。

【Flutter】文字の色(白・黒)を背景色に応じて変える

デモ

See the Pen flutter_estimate_brightness by popy1017 (@popy1017) on CodePen.

手順

1. 背景色が明色か暗色かを判定する

ThemeData.estimateBrightnessForColor(backgroundColor);を使う。

final Brightness brightness = ThemeData.estimateBrightnessForColor(backgroundColor);
final bool isLight = brightness == Brightness.light;

2. 判定結果に応じてTextの色を変える

TextStyle.colorを使う。

final Brightness brightness = ThemeData.estimateBrightnessForColor(backgroundColor);
final bool isLight = brightness == Brightness.light;
Text('Preview Card', style: TextStyle(
  color: isLight ? Colors.black : Colors.white,
)),