我有一个带有 TextField 的 AlertDialog。如果我提交我的 TextField,我希望 AlertDialog 弹出/消失。
我尝试将 () => Navigator.of(context).pop()
添加到我的 void on_submitted
,但它没有关闭 AlertDialog :(
我对 Flutter 和自学编程还很陌生,所以请放纵一下。
showDialog<CupertinoAlertDialog>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Gib den Spieler-Namen ein:',
style: TextStyle(
fontSize: 15,
fontFamily: 'ConcertOne'
),),
backgroundColor: Colors.blue[300],
content: Form(
key: formKey,
child: TextFormField(
controller: msgControllerClassic,
onFieldSubmitted: (String txt) => addSpieler(txt),
validator: (String value) {
if (value.isEmpty) { return 'Du hast nichts eingegeben';}
return null;
},
),
),
);
});
}
void addSpieler(String player) {
setState(() {
if (formKey.currentState.validate()) {
clearTextClassic();
Navigator.of(context).pop();
}});
}
AlertDialog is opend by a button-click. I now want the AlertDialog to vanish when submitting (addSpieler)
答案 0 :(得分:0)
我看不到您的 addSpieler
函数,但我假设您在其中调用了 Navigator.of(context).pop()
。请纠正我,我会相应地更新我的答案。
请注意,在 showDialog
中,有一个 builder
类型的参数 Widget Function(BuildContext)
。每次要对对话框上下文进行操作时,都应使用此参数提供的上下文。您可以按如下方式重构代码:
showDialog<CupertinoAlertDialog>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
// ...
child: TextFormField(
controller: msgControllerClassic,
// Use the context provided by builder here
onFieldSubmitted: (String txt) => addSpieler(context, txt),
validator: (String value) {
if (value.isEmpty) { return 'Du hast nichts eingegeben';}
return null;
},
),
);
});
);
还要重构您的 addSpieler
方法:
void addSpieler(BuildContext context, String txt) {
// ...
Navigator.of(context).pop();
}