繁体   English   中英

在 Flutter 中制作自定义小部件时,onPress 不起作用

[英]onPress not working when make Custom Widget in Flutter

我有一些问题不知道在制作自定义小部件 class 并通过 onpress function 时会发生什么,它不起作用。

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)),
        ),
      ),
    );
  }
}

我称之为小部件的地方。

RoundedButton(
          text: "LOGIN",
          press: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) {
                  return LoginScreen();
                },
              ),
            );
          },
        )

我试过但没有工作

onPressed: press()

onPressed: (){press;}

onPressed: () =>press

但是当我直接在 RoundButton 小部件上添加导航 function 时。

press: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) {
              return LoginScreen();
            },
          ),
        )

有效。

但不知道为什么自定义 function 不起作用。

我们唯一需要做的是 add.call() 到 function 的末尾是无效的。 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM