Flutter中没有上下文的AlertDialog [英] AlertDialog without context in Flutter
问题描述
我想在http获取失败时显示AlertDialog.函数showDialog( https://api.flutter.dev/flutter/material/showDialog.html)的参数为"@required BuildContext context",但是我想从我的异步函数getNews()调用AlertDialog,该函数没有上下文值.
I want to show an AlertDialog when a http get fails. The function showDialog (https://api.flutter.dev/flutter/material/showDialog.html) has the parameter "@required BuildContext context", but I want to call the AlertDialog from my async function getNews(), which hasn't a context value.
与Java类似,在没有所有者的情况下,我使用null进行对话时,我尝试将上下文值设置为null,但不接受.
By analogy with Java, where I use null for dialog without an owner, I tried to put context value to null, but it is not accepted.
这是我的代码:
Future<dynamic> getNews() async {
dynamic retVal;
try {
var response = await http.get(url));
if (response.statusCode == HttpStatus.ok) {
retVal = jsonDecode(response.body);
}
} catch (e) {
alertDlg(?????????, 'Error', e.toString());
}
return
retVal;
}
static Future<void> alertDlg(context, String titolo, String messaggio) async {
return showDialog<void>(
context: context,
barrierDismissible: false, // user must tap button!
builder: (BuildContext context) {
return AlertDialog(
title: Text(titolo),
...
);
}
推荐答案
接受的答案是错误的.
对话框仅需要上下文即可通过继承的navigationState访问它.您可以创建自己的修改对话框,也可以使用此lib来完成此操作.
The dialog only needs the context to access it through an inherited navigateState. You can make your own modified dialog, or use this lib to do this.
通过它,您可以从代码的任何位置打开对话框,而无需上下文:
With it you can open dialog from anywhere in your code without context by doing this:
Get.dialog(SimpleDialog());
这篇关于Flutter中没有上下文的AlertDialog的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!