Flutter有状态组件传递命名函数参数报错原因咨询
报错原因分析
核心原因:const构造与非常量参数冲突
你在创建ConversationsController时用了const关键字,但传递的switchScreenFn是_AuthenticationControllerState类的成员方法,属于运行时才确定的非编译期常量。而const构造要求所有传入的参数必须是编译期可确定的常量(比如字面量、全局常量等),成员方法不符合这个要求,因此触发报错。
解决步骤
- 移除
const关键字:将创建组件的代码修改为:
return ConversationsController( switchScreenToAuthenticationScreenFn: switchScreenFn, );
- 可选优化:明确函数类型:为了类型安全,建议把
ConversationsController的参数类型从模糊的Function?改为具体的函数类型:
class ConversationsController extends StatefulWidget { const ConversationsController({ this.switchScreenToAuthenticationScreenFn, super.key }); // 明确接收一个带int参数、无返回值的函数 final void Function(int)? switchScreenToAuthenticationScreenFn; @override State<ConversationsController> createState() => _ConversationsControllerState(); }
内容的提问来源于stack exchange,提问作者Sumchans
相关产品推荐
相关产品推荐

