在 Flutter 中制作自定义 Widget 时 onPress 不起作用

问题描述 投票:0回答:3

我有一些问题不知道当制作自定义小部件类并传递 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();
            },
          ),
        )

成功了。

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

android flutter click
3个回答
0
投票

我们唯一需要做的就是将 .call() 添加到函数的末尾以使其无效。 onPressed: ()=>onPressed 到 onPressed: ()=>onPressed.call()


0
投票

尝试在 RoundedButton 类中将

final Function press;
更改为
final VoidCallback press;
并保持其余代码不变。对我来说很好:)


-1
投票
@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)),
        ),
      ),
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.