您可以使用 Navigator API 返回模态结果。
文档显示了页面示例,但同样适用于模式/对话框页面
页面小部件
在您的情况下,在您的 ElevatedButton 上,等待 Navigator 响应:
class _MyWidgetState extends State<MyWidget> {
/// ...
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () {
/// Wait for the result with `await Navigator...` and store it on a variable
final result = await Navigator.of(context).push<String>(
PageRouteBuilder(
pageBuilder: (context, animation, secondaryAnimation) {
return IgnorePointer(
child: OnMoveDialog(),
);
},
opaque: false,
),
);
if (result == 'option-1') { /* Handle option 1 */ }
if (result == 'option-2') { /* Handle option 2 */ }
},
child: Text('Show dialog'),
);
}
/// ...
}
对话框小部件
在您的模态小部件中,弹出时返回值
class _MyModalState extends State<MyModalWidget> {
/// ...
@override
Widget build(BuildContext context) {
/// Pseudo Widget, is just to examplify your modal behavior
return MyModal(
children: [
Button(
'Option 1',
/// Here the magic happens, you need to pop the result
onTap: () => Navigator.pop<String>('option-1'),
),
Button(
'Option 2',
/// Same here, remeber: you can receive this callback as arguments
onTap: () => Navigator.pop<String>('option-2'),
),
],
);
}
/// ...
}