我在警报对话框中实现了4个单选按钮磁贴,并希望在选择任何一个单选按钮后将数据传递到“确定”按钮上,并将其显示在主屏幕上,或者可以通过共享首选项存储数据然后发送
class _MethodState extends State<Method> {
int _crtIndex = 1;
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text("Methods"),
content: ListView(
children: <Widget>[
RadioListTile(value: 1, groupValue: _crtIndex,
title: Text("A"),
activeColor: Colors.teal,
onChanged: (val){
setState(() {
_crtIndex = val;
});
}),
RadioListTile(value: 2, groupValue: _crtIndex,
title: Text("B"),
activeColor: Colors.teal,
onChanged: (val){
setState(() {
_crtIndex = val;
});
}),
RadioListTile(value: 3, groupValue: _crtIndex,
title: Text("C"),
activeColor: Colors.teal,
onChanged: (val){
setState(() {
_crtIndex = val;
});
}),
RadioListTile(value: 4, groupValue: _crtIndex,
title: Text("D"),
activeColor: Colors.teal,
onChanged: (val){
setState(() {
_crtIndex = val;
});
}),
actions: <Widget>[
new FlatButton(
child: new Text('OK'),
onPressed: () {
// pass data
Navigator.of(context).pop();
},
),
答案 0 :(得分:1)
您可以使用此https://pub.dev/packages/shared_preferences
onPressed: () async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setInt('radio.value', _crtIndex);
Navigator.of(context).pop();
}
并在应用程序中的任何位置获取它
getSelectedValue() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
int radioValue = prefs.getInt('radio.value');
// check if radioValue is null - no button is pressed yet, otherwise you will have selected radio value here.
}
答案 1 :(得分:0)
从主屏幕打开AlertDialog
时,您可以将函数作为参数传递,并在OK
中按AlertDialog
来调用此函数。
这是一个例子。
class Method extends StatefulWidget {
Function functionFromMain;
Method({Key key, @required this.functionFromMain}) : super(key: key);
}
现在,按您的代码,在按OK
时在下面添加一行。
onPressed: () {
widget.functionFromMain(_crtIndex);
Navigator.of(context).pop();
},
现在在您的Main类中打开此Method小部件时,
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Method(functionFromMain: yourFunction,)));