Flutter报const列表字面量需为常量/无效常量值错误如何解决?
问题原因
你贴出的这段代码本身没有语法错误,报错是因为这段Expanded组件的父组件、或者它所在的子元素列表被加了const修饰符。
Dart语法规定const声明的常量组件,内部所有属性都必须是编译时常量,而你给TextButton传入的onPressed匿名函数() {}是运行时生成的,不属于编译时常量,因此触发了常量校验失败的报错。
解决方法
- 最简单的处理方式是直接删除外层包裹这段代码的
const修饰符即可,比如你的父结构类似下面这种写法,删掉children前的const就可以正常编译:
Row( // 删掉这里的const children: const [ // 你的Expanded代码写在这 ] )
- 如果确实需要保留
const的性能优化,也可以把空回调提前定义为类的静态常量函数:
class YourWidget extends StatelessWidget { // 预先定义静态常量空回调 static const VoidCallback _emptyPress = _handleEmptyPress; static void _handleEmptyPress() {} @override Widget build(BuildContext context) { return Row( children: const [ Expanded( child: TextButton( // 传入预先定义的常量回调 onPressed: _emptyPress, child: Padding( padding: EdgeInsets.all(16.0), child: Image( image: AssetImage('images/dice1.png'), ) ), ), ) ], ); } }
内容的提问来源于stack exchange,提问作者chogyal
相关产品推荐
相关产品推荐

