[英]Flutter Switch doesn't work in Modalbottomsheet
我的設置:
class Start_Page extends StatefulWidget {
@override
StartPageState createState() => StartPageState();
}
class StartPageState extends State<Start_Page> {
@override
Widget build(BuildContext context){
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
return Scaffold(
body: Container(
child: ElevatedButton(
style: ButtonStyle(),
onPressed: () {
createUserModalBottomSheet(context);
},
child: Text("Start"),
)
)
);
}
}
void createUserModalBottomSheet(context){
showModalBottomSheet(context: context, builder: (BuildContext bc) {
return Container(
child: Switch(value: true, onChanged: (value) => {value = !value}, activeColor:
Colors.grey)
);
}
}
問題是開關不會改變他的價值。 Modalbottomsheet 出現但不會更新更改/狀態。 有誰知道解決方案?
使用StatefulBuilder
更新showModalBottomSheet
內的 UI。 第二個問題是您需要使用 bool 變量來保存值。
class StartPageState extends State<Start_Page> {
bool switchValue = false;
///......
void createUserModalBottomSheet(context) {
showModalBottomSheet(
context: context,
builder: (BuildContext bc) {
return StatefulBuilder(
builder: (context, setStateSB) => Container(
child: Switch(
value: switchValue,
onChanged: (value) {
setState(() {
// update parent UI
switchValue = value;
});
setStateSB(() {
// update inner dialog
switchValue = value;
});
},
activeColor: Colors.grey),
),
);
});
}
@override
Widget build(BuildContext context) {
.........
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.