我想更改 MyButton 中文本字段的值,這樣,每次單擊按鈕時,該值都會更改。我已將該值設置為 MyButton 中的一個屬性,並將一個函數從 MyButtonRow 傳遞給 MyButton,該函數將在每次單擊時執行。在該函數中,我想更改 MyButton 的屬性“myString”,因此它會自動更新文本字段。
代碼:
class MyButtonRow extends StatefulWidget {
const MyButtonRow({Key? key}) : super(key: key);
@override
_MyButtonRowState createState() => _MyButtonRowState();
}
class _MyButtonRowState extends State<MyButtonRow> {
@override
Widget build(BuildContext context) {
return Container(width: MediaQuery.of(context).size.width,
child: Row(children: <Widget>[MyButton(onTap: (){
print("Notify me");
//I want to change the myText attribute of MyButton here
}, myText: "Hello",)],));
}
}
class MyButton extends StatefulWidget {
final Function onTap;
final String myText;
const MyButton({Key? key, required this.onTap, required this.myText}) : super(key: key);
@override
_MyButtonState createState() => _MyButtonState();
}
class _MyButtonState extends State<MyButton> {
var onTap;
var myString;
@override
void initState() {
onTap = widget.onTap;
myString = widget.myText;
super.initState();
}
@override
Widget build(BuildContext context) {
return TextButton(onPressed:onTap,
child: Text(myString));
}
}
問題是您將 newValue 作為構造函數參數傳遞並將其分配給保持狀態的局部變量。每當調用重建時, initState 函數永遠不會再次調用,只是第一次,我建議不要使用:
@override
Widget build(BuildContext context) {
return TextButton(onPressed:onTap,
child: Text(myString));
}
你繼續使用:
@override
Widget build(BuildContext context) {
return TextButton(onPressed:onTap,
child: Text(widget.myText));
}
在這種情況下,只要父級重建您的小部件,該值就會更新。有道理?
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句