Flutter:向自定义Button Widget传参时遇常量表达式错误
问题解答
错误原因
你遇到的「Not a constant expression」错误,核心问题在于:const Text() 要求所有传入的参数必须是编译阶段就能确定的常量,但你传入的 title 是组件实例的成员变量,它的值是在运行时由父组件传入的,不属于编译期常量,所以无法满足 const 构造的要求。哪怕你写 const title 也没用,因为 title 本身就不是编译常量。
修复方法
直接移除 Text 组件前面的 const 关键字即可,因为这个文本内容依赖于外部传入的参数,不需要被声明为编译时常量:
修改后的关键代码片段:
// 原来的代码 child: const Text( 'Login', style: TextStyle( color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold, ), ), // 修改后 child: Text( title, // 这里使用传入的title参数 style: const TextStyle( // 这里的TextStyle可以保留const,因为它的参数都是编译常量 color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold, ), ),
完整修复后的MyCustomButton代码
import 'package:flutter/material.dart'; class MyCustomButton extends StatelessWidget{ final String title; final String type; const MyCustomButton({ super.key, required this.title, required this.type, }); @override Widget build(BuildContext context) { return Container( padding: const EdgeInsets.fromLTRB(35, 15, 35, 15), margin: const EdgeInsets.symmetric(horizontal: 20), decoration: const BoxDecoration( color: Color.fromRGBO(112, 143, 164, 1), borderRadius: BorderRadius.all(Radius.circular(4)), ), child: Text( title, style: const TextStyle( color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold, ), ), ); } }
额外说明:你的MyCustomButton本身可以保留const构造,只要调用它时传入的title和type是常量(比如你示例中的字符串字面量),这完全没问题,组件的const和内部子组件的const是独立的。
内容的提问来源于stack exchange,提问作者lechnerio
相关产品推荐
相关产品推荐

