Flutter常量构造器报错:Null无法赋值给List<Color>参数
错误原因
这两个错误的核心是同一个问题:const构造器要求所有参数必须是编译时常量。你的gradientColors是组件从外部接收的参数,它的值在组件运行时才会确定,不属于编译阶段就能固定的常量,因此无法被const BoxDecoration和const LinearGradient使用。
解决方法
直接移除BoxDecoration和LinearGradient前面的const关键字即可——因为这两个对象依赖的gradientColors不是编译常量,不能用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( // 移除const关键字 gradient: LinearGradient( // 移除const关键字 begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: gradientColors ) ), ), ), 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') ), ], ), ); } }
内容的提问来源于stack exchange,提问作者Jamie
相关产品推荐
相关产品推荐

