Flutter SlidableAction的onPressed回调异常触发解决方法
问题根因
给onPressed传参时错误添加了函数调用括号(),直接导致两个异常现象:
- 组件构建阶段会立刻执行
deletTransact()、editTransact()函数,也就是你观察到的构建阶段自动执行的问题 - 这两个函数没有定义返回值,默认返回
null,最终onPressed被赋值为null,组件渲染完成后点击时自然不会触发任何响应
修复方法
SlidableAction的onPressed回调要求的函数签名为void Function(BuildContext context),有两种可行改法:
方式一:匿名函数包裹(无需修改原有业务函数)
传入符合签名要求的匿名函数,在函数内部调用你写好的业务方法即可,修正后核心代码:
SlidableAction( onPressed: (context) { deletTransact(); }, backgroundColor: Color(0xFFFE4A49), foregroundColor: Colors.white, icon: Icons.delete, label: 'Delete', ), SlidableAction( flex: 2, onPressed: (context) { editTransact(); }, backgroundColor: Color(0xFF2196f3), foregroundColor: Colors.white, icon: Icons.edit, label: 'Edit', ), // 原有业务函数无需改动 deletTransact() { print("delete"); } editTransact() { print("edit"); }
如果逻辑足够简单,还可以用箭头函数简写:
onPressed: (context) => deletTransact(),
方式二:调整业务函数签名,直接传函数引用
如果业务逻辑中需要使用上下文对象(比如弹框、路由跳转),可以直接把业务函数的参数改成和回调要求一致的格式,直接传函数名即可(注意不要加括号):
SlidableAction( onPressed: deletTransact, backgroundColor: Color(0xFFFE4A49), foregroundColor: Colors.white, icon: Icons.delete, label: 'Delete', ), SlidableAction( flex: 2, onPressed: editTransact, backgroundColor: Color(0xFF2196f3), foregroundColor: Colors.white, icon: Icons.edit, label: 'Edit', ), // 补全匹配的参数 deletTransact(BuildContext context) { print("delete"); // 可通过context获取当前组件上下文做后续操作 } editTransact(BuildContext context) { print("edit"); }
通用规则:Flutter中所有回调类型参数传值时,带括号
()代表立刻执行函数、传递返回值;不带括号代表传递函数引用,等待交互触发时才执行。如果自定义函数的参数和回调要求的签名不匹配,就用匿名函数做一层包装即可。
内容的提问来源于stack exchange,提问作者Hamza A Masharqah
相关产品推荐
相关产品推荐

