gpt4 book ai didi

android - 如何在创建的 RaisedButton 对象中设置函数?

转载 作者:IT王子 更新时间:2023-10-29 07:04:36 25 4
gpt4 key购买 nike

我正在使用 firebase_auth 在 flutter 中创建一个应用。

我有一个用于 View 的“登录”类和用于按钮和输入的其他“元素”类。我试图在 Elements 类的一个按钮上的 Login 类中设置一个函数,但我不知道如何从一个按钮设置一个函数到另一个。有人可以帮助我吗?

谢谢!

class Elements {
RaisedButton buttonPrimaryFilled(String _text) {
return new RaisedButton(
onPressed: (){

},
elevation: 4,
color: Colors.red,
child: new Container(
child: new Center(
child: new Text(_text,
textAlign: TextAlign.center,
style: new TextStyle(fontSize: 23,
color: Colors.white,
letterSpacing: 2,
fontWeight: FontWeight.bold
)
),
),
width: 350,
height: 50,
),
textColor: Colors.white,

);
}

}



class _LoginPageSate extends State<LoginPage> {

@override
Widget build(BuildContext context) {

//Button login
RaisedButton btnLogin = this.myElements.buttonPrimaryFilled("Iniciar sesión");

return new Scaffold(
body: new SingleChildScrollView(
child: new Center(

child: new Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,

children: <Widget>[

//Here is the problem
btnLogin.onPressed,

]

),
),
),
),
}

}

最佳答案

首先,我强烈建议您为按钮使用扩展 (Stateless|Stateful)Widget 的特定类,而不是 Elements 类。

让我们为您的按钮创建一个 StatelessWidget,并允许向其传递参数

class PrimaryButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
return // Your button here;
}
}

之后,您需要允许您的 PrimaryButton 类接收事件的回调

class PrimaryButton extends StatelessWidget {
PrimaryButton({this.onClick, this.child});
final String child;
final Function() onClick;

// ....
}

在您的构建方法中,您可以使用收到的这些属性

  @override
Widget build(BuildContext context) {
return new RaisedButton(
onPressed: onClick,
elevation: 4,
color: Colors.red,
child: new Container(
width: 350,
height: 50,
child: new Center(
child: new Text(
text,
textAlign: TextAlign.center,
style: new TextStyle(
fontSize: 23,
color: Colors.white,
letterSpacing: 2,
fontWeight: FontWeight.bold
)
),
),
),
textColor: Colors.white,
);
}

要完成它,就在您需要的地方调用您的 PrimaryButton

  @override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
PrimaryButton(
child: Text('Iniciar sesión'),
onClick: () { /* your function */ },
)
]
),
),
),
);
}

关于android - 如何在创建的 RaisedButton 对象中设置函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54515423/

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