首页 > 解决方案 > 如何从 Flutter 中的“ThemeData”中检索“MaterialColor”而不是“Color”?

问题描述

我想要实现的是使用颜色样本在画布上进行绘画,并使用动态计算的阴影指数来利用当前应用主题中特定样本的不同阴影。

    int colorIndex = 700;
    Paint paintFill = Paint()
      ..style = PaintingStyle.fill
      ..strokeWidth = 6.0
      ..color = (Theme.of(_context).primaryColor as MaterialColor)[colorIndex];
    for (int i = currentHour12; i >= 0; i--) {
      angleInDegrees = 30 * i;
      angleInRadians = (angleInDegrees-90) * pi / 180.0;
      canvas.drawArc(
          Rect.fromCircle(center: centerCurrent, radius: radius),
          angleInRadians,
          -angleSweepInRadians,
          true,
          paintFill
      );
      if (i % 2 == 0) colorIndex -= 100;
      paintFill = Paint()
        ..style = PaintingStyle.fill
        ..strokeWidth = 6.0
        ..color = (Theme.of(_context).primaryColor as MaterialColor)[colorIndex];
    }

使用上面的当前代码,它可以工作,但有一个有意义的错误:

类型“Color”不是类型转换中“MaterialColor”类型的子类型

在我的主题primaryColor中设置为MaterialColor

final darkTheme = ThemeData(
  brightness: Brightness.dark,
  primaryColor: Colors.indigo,
  ...
)

但它被检索为一个简单Color的代码如下:

(Theme.of(_context).primaryColor as MaterialColor)[colorIndex]

我也尝试检索 a 的primarySwatch属性ThemeData,但它似乎是私有的。

有没有办法从 a 中获取整个样本ThemeData?或者以某种方式将Color后面的类型转换为MaterialColor?

标签: flutterflutter-layout

解决方案


所以我最终写了一个辅助函数:

MaterialColor getMaterialColor(Color color) => Colors.primaries
  .firstWhere((element) => element.value == color.value);

这被称为如下:

int colorIndex = 700;
MaterialColor primarySwatch = getMaterialColor(Theme.of(_context).primaryColor);
Paint paintFill = Paint()
  ..style = PaintingStyle.fill
  ..strokeWidth = 6.0
  ..color = primarySwatch[colorIndex];

推荐阅读