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.
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.
This is my code:
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),
...
);
}
Build
context fromStatefulWidget
where you'll display the http response to yourgetNews()
function . – Lumenhour