android - 在 Flutter 中制作自定义小部件时 onPress 不起作用
问题描述
我有一些问题不知道在制作自定义小部件类并传递 onpress 功能时会发生什么不工作。
RoundButton 飞镖文件
class RoundedButton extends StatelessWidget {
final String text;
final Function press;
final Color color, textColor;
const RoundedButton({
Key? key,
required this.text,
required this.press,
this.color = primaryColor,
this.textColor = Colors.white,
}) : super(key: key);
@override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Container(
margin: EdgeInsets.symmetric(vertical: 8),
width: size.width * 0.8,
child: ClipRRect(
borderRadius: BorderRadius.circular(30),
child: TextButton(
onPressed: press(),
child: Text(text),
style: TextButton.styleFrom(
backgroundColor: color,
primary: textColor,
padding: EdgeInsets.symmetric(vertical: 16, horizontal: 40)),
),
),
);
}
}
我称之为小部件的地方。
RoundedButton(
text: "LOGIN",
press: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return LoginScreen();
},
),
);
},
)
我试过但没有工作
onPressed: press()
onPressed: (){press;}
onPressed: () =>press
但是当我直接在 RoundButton 小部件上添加导航功能时。
press: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return LoginScreen();
},
),
)
有效。
但不知道为什么自定义功能不起作用。
解决方案
@override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Container(
margin: EdgeInsets.symmetric(vertical: 8),
width: size.width * 0.8,
child: ClipRRect(
borderRadius: BorderRadius.circular(30),
child: TextButton(
onPressed: press(), // call just press ,here u r calling the func // right after the widget is rendered. Its worked fine for me in versions b4 //null safety.
child: Text(text),
style: TextButton.styleFrom(
backgroundColor: color,
primary: textColor,
padding: EdgeInsets.symmetric(vertical: 16, horizontal: 40)),
),
),
);
}
}
推荐阅读
- java - 如何将 JSON 拆分为数据集行?
- php - Laravel 5.7 视图中未定义的变量
- sql-server - SSRS - Windows 文件共享
- javascript - 为什么 Vuejs 不注册启用或禁用我的按钮?
- android - 添加到 RelativeLayout 时更改 GridView
- javascript - 用php重定向选中的复选框并使其工作
- python - 通过 SSL/TLS 的 FTP/FXP 服务器到服务器传输
- kubernetes - 以声明方式(在 yaml 中)自动扩展 google Cloud-Endpoints 后端部署?
- java - Weblogic 12c 中如何处理异常?
- apache-kafka - Kafka Connect Hdfs Sink 连接器 - 找不到类 io.confluent.connect.hdfs.string.StringFormat