flutter - 如何从 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
?
解决方案
所以我最终写了一个辅助函数:
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];
推荐阅读
- python - 解决 ModuleNotFoundError:没有名为“abc”的模块
- python - bytearray 中的 ascii 字符而不是十六进制值
- webpack - Webpack Aurelia - 如何配置并非所有块都与 Aurelia 捆绑在一起?
- vb.net - Visual Studio 2019 - VB - 创建可注册的 COM 对象
- installation - 使用 pip 安装 annoy 时如何解决错误?
- java - 将 log4j 添加到 build.gradle
- r - R中的循环密度曲线
- java - 创建名为“***.jpa.HibernateJpaConfiguration”的 bean 时出错
- javascript - 将变量分配给firestore值检查
- python - 表格出现之前的QtableView占位符文本