gpt4 book ai didi

dart - 将方法作为参数传递给小部件

转载 作者:IT王子 更新时间:2023-10-29 06:53:58 26 4
gpt4 key购买 nike

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

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

然后在父 Widget 中,我想将 onPressed 方法传递给此按钮小部件:

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

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

最佳答案

使用 VoidCallback 类型,像这样。查看代码的行注释以获取更多信息:

class Button extends StatelessWidget {
final String text;
final VoidCallback callback; // Notice the variable type

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

关于dart - 将方法作为参数传递给小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54493002/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com