Flutter中如何重构函数?以自定义OutlinedButton的onPressed逻辑为例
问题原因
你当前代码的问题主要有两点:
- Dart空安全规则下,命名参数默认是可选状态,你声明的
void Function() onpressedAction是非空类型,没有加required标识也没有设置默认值,编译时会直接报错。 - 你目前
OutlinedButton的onPressed还是硬编码的打印逻辑,并没有绑定你声明的onpressedAction参数,传入的点击事件根本不会生效。
重构方案
根据你的使用场景可以二选一:
方案1:要求必须传入点击逻辑(必填参数)
给onpressedAction加required修饰,直接绑定到按钮的点击事件即可,完整代码如下:
import 'package:flutter/material.dart'; Widget justButton({ String btText = '', Color bgColor = Colors.blue, Color? txtColor = Colors.white, Color borderColor = Colors.black, // 加required标记为必填命名参数 required void Function() onpressedAction, }) { return OutlinedButton( // 直接绑定传入的点击函数 onPressed: onpressedAction, child: Text(btText), style: OutlinedButton.styleFrom( backgroundColor: bgColor, primary: txtColor, side: BorderSide(color: borderColor)), ); }
调用示例:
justButton( btText: "跳转到事件页", onpressedAction: () { print('Go to events Page'); // 你可以在这里写其他点击逻辑 }, )
方案2:允许不传点击逻辑(可选参数)
如果允许使用按钮的时候不传点击事件,就把参数类型改成可空函数,绑定的时候做空判断即可:
import 'package:flutter/material.dart'; Widget justButton({ String btText = '', Color bgColor = Colors.blue, Color? txtColor = Colors.white, Color borderColor = Colors.black, // 改成可空函数类型 void Function()? onpressedAction, }) { return OutlinedButton( // 空的话传null,按钮会自动变为不可点击状态,也可以自己写默认逻辑 onPressed: onpressedAction, child: Text(btText), style: OutlinedButton.styleFrom( backgroundColor: bgColor, primary: txtColor, side: BorderSide(color: borderColor)), ); }
内容的提问来源于stack exchange,提问作者Leskeboy
相关产品推荐
相关产品推荐

