错误 无法将类型为"颜色?"的值分配给颤振中类型为"颜色"的变量

  • 本文关键字:颜色 类型 变量 分配 错误 flutter
  • 更新时间 :
  • 英文 :


我有一个名为CircleIcon的小部件,我试图通过命名参数添加bgcolor。

class CircleIcon extends StatelessWidget {
final IconData icon;
final double iconSize;
final Color bgColor;
final VoidCallback onPressed;
const CircleIcon({
Key? key,
required this.icon,
this.iconSize = 25.0,
this.bgColor = Colors.grey[200],
required this.onPressed,
}) : super(key: key);

作为一个默认的bg颜色,我试图保持颜色。灰色[200],但我得到错误A value of type 'Color?' can't be assigned to a variable of type 'Color'.如果我把它改成颜色。灰色,那它起作用了。颜色的类型是什么?灰色[200]?

试试下面的代码,希望对你有所帮助。

Colors.grey[200]not constant如果你使用简单的Colors.grey接受所以我使用const值像constColor(0xFFEEEEEE)

class CircleIcon extends StatelessWidget {  
final IconData icon;
final double iconSize;
final Color  bgColor;
final VoidCallback onPressed;
const CircleIcon({
Key? key,
required this.icon,
this.iconSize = 25.0,
this.bgColor = const Color(0xFFEEEEEE),
required this.onPressed,
}) : super(key: key);
}

参考我的答案here

参考扑色here

您在CircleIcon之前使用const,并且使用Colors.blue[100]意味着读取映射,这不是恒定的。它将在运行时获取数据。

你可以在GitHub上探索

static const MaterialColor grey = MaterialColor(
_greyPrimaryValue,
<int, Color>{
50: Color(0xFFFAFAFA),
100: Color(0xFFF5F5F5),
200: Color(0xFFEEEEEE),
//....
},
);

因此,您不能使用const与color[value].

grey[200]Color(0xFFEEEEEE),时,你可以使用它。

this.bgColor = const Color(0xFFEEEEEE),

问题在于空值。您需要定义bgColor为可空类型

final Color? bgColor;

您可以使用(!)操作符:

this.bgColor = Colors.grey[200]!

使用shade的颜色:

this.bgColor = Colors.grey.shade200

您正在读取地图,该颜色无法处理。

使用Colors.grey.shade200Color(0xFFEEEEEE)