将方法作为参数传递给小部件 [英] Pass method as parameter to a widget

查看:50
本文介绍了将方法作为参数传递给小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义按钮小部件:

I have a custom button widget:

class Button extends StatelessWidget {
  final String text;

  Button(this.text);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 50,
      child: SizedBox(
        width: double.infinity,
        child: RaisedButton(
          onPressed: () => {}, // Use the function from parent Widget
          child: Padding(
              padding: EdgeInsets.symmetric(vertical: 13),
              child: Text(
                text,
                style: TextStyle(fontWeight: FontWeight.bold),
              )),
          color: COLOR_BLUE,
          textColor: Colors.white,
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(25)),
        ),
      ),
    );
  }
}

然后在父窗口小部件中,我想向该按钮窗口小部件传递onPressed方法:

Then in parent Widget I want to pass a onPressed method to this button widget:

...
myMethod () => {
   // do some stuff
}
...
Padding(
    padding: EdgeInsets.only(bottom: 10),
    child: Button("Log in", myMethod),
),
...

如何告诉按钮小部件将myMethod用于onPress?

How can I tell to a button widget to use the myMethod for onPress?

推荐答案

使用VoidCallback类型,如下所示:

class Button extends StatelessWidget {
  final String text;
  final VoidCallback callback;

  Button(this.text, this.callback);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 50,
      child: SizedBox(
        width: double.infinity,
        child: RaisedButton(
          onPressed: callback, // Simply put the function name here, DON'T use ()
          child: Padding(
              padding: EdgeInsets.symmetric(vertical: 13),
              child: Text(
                text,
                style: TextStyle(fontWeight: FontWeight.bold),
              )),
          color: COLOR_BLUE,
          textColor: Colors.white,
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(25)),
        ),
      ),
    );
  }
}

这篇关于将方法作为参数传递给小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆