我有一个小部件,它接受我需要在我的小部件中使用的颜色数组。我不明白为什么它总是给我下面的错误。
我的小部件如下所示;
class RoundedGradientButton extends StatelessWidget {
const RoundedGradientButton({
required this.gradientColors,
super.key,
});
final List<Color> gradientColors;
@override
Widget build(BuildContext context) {
return ClipRRect(
borderRadius: BorderRadius.circular(20),
child: Stack(
children: <Widget>[
Positioned.fill(
child: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: this.gradientColors // -> Complains
)
),
),
),
TextButton(
style: TextButton.styleFrom(
foregroundColor: Colors.white,
padding: const EdgeInsets.only(top: 10, bottom: 10),
textStyle: const TextStyle(fontSize: 16),
minimumSize: const Size.fromHeight(0)),
onPressed: () {},
child: const Text('Start')
),
],
),
);
}
}
- 不能将'Null'类型的值赋给const构造函数中'List'类型的形参。尝试使用子类型,或删除关键字"const"。
- 无效的常量值。
对于您的第一个问题,当您使用RoundedGradientButton
时,似乎您正在传递空值,请确保您这样调用它:
RoundedGradientButton(gradientColors: [your color]);
对于第二个问题,gradientColors
变量不是恒定的,所以你需要在BoxDecoration
之前删除const
关键字,你的完整代码将是这样的:
class RoundedGradientButton extends StatelessWidget {
const RoundedGradientButton({
required this.gradientColors,
super.key,
});
final List<Color> gradientColors;
@override
Widget build(BuildContext context) {
return ClipRRect(
borderRadius: BorderRadius.circular(20),
child: Stack(
children: <Widget>[
Positioned.fill(
child: Container(
decoration: BoxDecoration( // remove const from here
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: gradientColors, // change this
),
),
),
),
TextButton(
style: TextButton.styleFrom(
padding: const EdgeInsets.only(top: 10, bottom: 10),
textStyle: const TextStyle(fontSize: 16),
minimumSize: const Size.fromHeight(0)),
onPressed: () {},
child: const Text('Start')),
],
),
);
}
}
删除此处的const
const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: this.gradientColors // -> Complains
)
问题是使用const
并试图在运行时获得变量。如果您注意到错误消息,它包含
'List'。尝试使用子类型,或
removing the keyword 'const
'。
在BoxDecoration
之前删除const
Positioned.fill(
child: Container(
decoration: BoxDecoration( //this line `const`
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: gradientColors)),
),
),