[英]BottomSheet value does not update using button flutter
我有一個底部表,其中包含一組按鈕。 我使用按鈕更改 pinString 的值和顯示pinString
的pinString
。 單擊按鈕時,文本的值不會更新。 如何解決這個問題
showNumberPad(BuildContext context) {
showModalBottomSheet(
context: context,
builder: (context) {
return StatefulBuilder(builder: (context, setState) {
return Container(
height: 550.0,
child: Column(
children: <Widget>[
Text(
"$pinString",
),
KeyboardNumber(
n: 1,
onPressed: () {
pinIndexSetup("1");
setState1() {
pinString = "New Pin";
}
},
),
],
),
);
});
},
);
}
KeyboardNumber 是一個自定義的有狀態小部件,我想將 onPressed 作為參數傳遞。 鍵盤編號代碼:
class KeyboardNumber extends StatefulWidget {
final int n;
final onPressed;
const KeyboardNumber({Key key, this.n, this.onPressed}) : super(key: key);
@override
_KeyboardNumberState createState() => _KeyboardNumberState();
}
class _KeyboardNumberState extends State<KeyboardNumber> {
@override
Widget build(BuildContext context) {
return Container(
width: 60.0,
height: 60.0,
decoration: BoxDecoration(
color: teal2,
borderRadius: BorderRadius.all(
Radius.circular(10),
),
),
alignment: Alignment.center,
child: FlatButton(
padding: EdgeInsets.all(8.0),
onPressed: widget.onPressed,
height: 90.0,
child: Text(
"${widget.n}",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
),
);
}
}
您在另一個state 中定義 pinString 並在bottomeSheet state中更改它,您必須在此行中定義它:
showModalBottomSheet(
context: context,
builder: (context) {
String pinString = 'hi';
return StatefulBuilder(builder: (BuildContext context, StateSetter setState){
return Container(
height: 550.0,
child: Column(
children: <Widget>[
Text(
"$pinString",
),
FlatButton(
child: Text("Update"),
onPressed: () {
setState(() => pinString = 'new');
},
),
],
),
);
});
},
);
}
請注意,新的setState
將覆蓋您的主小部件setState
但確保您可以重命名它,以便您能夠設置父小部件的 state 和模態的
這是更新的代碼。
showNumberPad(BuildContext context) {
showModalBottomSheet(
context: context,
builder: (context) {
return StatefulBuilder(builder: (context, SetState1) {
return Container(
height: 550.0,
child: Column(
children: <Widget>[
Text(
"$pinString",
),
FlatButton(
child: Text("Update"),
onPressed: () {
SetState1(() {
pinString = "New Pin";
});
},
),
],
),
);
});
},
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.