gpt4 book ai didi

flutter - 将参数传递给initState Flutter/Dart?

转载 作者:行者123 更新时间:2023-12-03 04:28:04 25 4
gpt4 key购买 nike

我是Flutter的新手,所以不确定是否可以...

我正在尝试在MaterialDesignIcon RaisedButton的基础上自定义statefulWidget。

我想简单地在凸起按钮的实例中传递两个参数。

因此,当我创建RaisedButton时,我可以做如下操作:

RaisedButton(backgroundColor: Colors.grey, text: 'Press me')

请在下面查看我尝试制作的代码。
class CustomRaisedButton extends StatefulWidget {

@override
CustomRaisedButtonState createState() => CustomRaisedButtonState();
}

void buttonPressed() {
print('A FUNCTION WOULD GO HERE');
}

class CustomRaisedButtonState extends State<CustomRaisedButton> {
var _backgroundColor = Colors.transparent;
var _text = String;
var _hoverColor = Colors.transparent;

@override
void initState(backgroundColor, text) { < ---- // Can I put the parameters required here?
super.initState();

this._backgroundColor = backgroundColor;
this._text = text;

if (_backgroundColor != Colors.grey) {
_textColor = Colors.white;
}
if (_backgroundColor == Colors.grey) {
_hoverColor = Colors.black54;
}
if (_backgroundColor == Colors.red) {
_hoverColor = Colors.deepOrangeAccent;
}
if (_backgroundColor == Colors.lightGreen) {
_hoverColor = Colors.green;
}
}

@override
Widget build(BuildContext context) {
// TODO: implement build
return RaisedButton(
onPressed: buttonPressed,
color: _backgroundColor,
textColor: Colors.black,
disabledColor: Colors.black38,
disabledTextColor: _textColor,
disabledElevation: 4,
elevation: 4,
hoverColor: _hoverColor,
padding: const EdgeInsets.all(8.0),
child: Text('$_text', style: CustomTextStyle.display1(context))
);
}
}

这似乎是一个愚蠢的问题,因为我知道您仍然可以在自定义小部件实例化的参数中访问这些属性。但是我想根据backgroundColor更改按钮的不同属性。提前致谢。

最佳答案

您可以使用widget.访问有状态窗口小部件中的窗口小部件属性:

class ExampleWidget extends StatefulWidget {

final String data;
const ExampleWidget({Key key, this.data}) : super(key: key);

@override
_ExampleWidgetState createState() => _ExampleWidgetState();
}

class _ExampleWidgetState extends State<ExampleWidget> {

String text;

@override
void initState() {
super.initState();
text = widget.data.substring(0,2).toUpperCase();
}

@override
Widget build(BuildContext context) {
return Text(text);
}
}

关于flutter - 将参数传递给initState Flutter/Dart?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57996486/

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