Flutter 如何在flatter中从“主题数据”中检索“MaterialColor”而不是“Color”?
我试图实现的是使用一个色样在画布上进行绘制,并使用动态计算的着色指数,以利用当前应用主题中特定色样的不同着色Flutter 如何在flatter中从“主题数据”中检索“MaterialColor”而不是“Color”?,flutter,flutter-layout,Flutter,Flutter Layout,我试图实现的是使用一个色样在画布上进行绘制,并使用动态计算的着色指数,以利用当前应用主题中特定色样的不同着色 int colorIndex = 700; Paint paintFill = Paint() ..style = PaintingStyle.fill ..strokeWidth = 6.0 ..color = (Theme.of(_context).primaryColor as MaterialColor)[colorIndex]
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];
}
对于上面的当前代码,它可以工作,但存在一个有意义的错误:
类型“颜色”不是类型转换中“MaterialColor”类型的子类型
在我的主题中,primaryColor
设置为MaterialColor
:
final darkTheme = ThemeData(
brightness: Brightness.dark,
primaryColor: Colors.indigo,
...
)
但它被检索为一种简单的颜色
,代码如下:
(Theme.of(_context).primaryColor as MaterialColor)[colorIndex]
我还尝试检索主题数据的主样本
属性,但它似乎是私有的
有没有办法从主题数据中获取整个样本?或者以某种方式将颜色
键入回材质颜色
?,因此我最终编写了一个助手函数:
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];