[英]onPress not working when make Custom Widget in Flutter
i have some issue don't know what happanning when make custom widget class and pass onpress function its not working.我有一些问题不知道在制作自定义小部件 class 并通过 onpress function 时会发生什么,它不起作用。
RoundButton dart file RoundButton dart文件
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)),
),
),
);
}
}
Where I call that widget.我称之为小部件的地方。
RoundedButton(
text: "LOGIN",
press: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return LoginScreen();
},
),
);
},
)
I tried like but not working我试过但没有工作
onPressed: press()
onPressed: (){press;}
onPressed: () =>press
But when I add the Navigation function directly at the RoundButton widget.但是当我直接在 RoundButton 小部件上添加导航 function 时。
press: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return LoginScreen();
},
),
)
It worked.有效。
But don't know why custom function not working.但不知道为什么自定义 function 不起作用。
the only we need to do is add.call() to the end of the function to be void.我们唯一需要做的是 add.call() 到 function 的末尾是无效的。 onPressed: ()=>onPressed to onPressed: ()=>onPressed.call() onPressed: ()=>onPressed 到 onPressed: ()=>onPressed.call()
@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)),
),
),
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.