I am fetching data from api in getSmartTags()
And if error occurs, I want to show the dialog.
I made the code below but this error comes.
lib/main.dart:1218:14: Error: Undefined name 'context'. context: context,
^^^^^^^
@override
Widget build(BuildContext context) {
context is in build function, but I want to show the alert dialog not in build function, is it possible?
Future<void> _showMyDialog() async {
return showDialog<void>(
context: context,
barrierDismissible: false, // user must tap button!
builder: (BuildContext context) {
return AlertDialog(
title: const Text('AlertDialog Title'),
content: SingleChildScrollView(
child: ListBody(
children: const <Widget>[
Text('This is a demo alert dialog.'),
Text('Would you like to approve of this message?'),
],
),
),
actions: <Widget>[
TextButton(
child: const Text('Approve'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
Future getSmartTags() async {
var url = Uri.https(apiServer,'/api/smarttags');
try{
var resp = await http.get(url);
throw Exception();
}catch(e){
_showMyDialog();
}
}
CodePudding user response:
Try this
//add context as parameter
Future<void> _showMyDialog(BuildContext context) async {
return showDialog<void>(
context: context,
barrierDismissible: false, // user must tap button!
builder: (BuildContext context) {
return AlertDialog(
title: const Text('AlertDialog Title'),
content: SingleChildScrollView(
child: ListBody(
children: const <Widget>[
Text('This is a demo alert dialog.'),
Text('Would you like to approve of this message?'),
],
),
),
actions: <Widget>[
TextButton(
child: const Text('Approve'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
Future getSmartTags() async {
var url = Uri.https(apiServer,'/api/smarttags');
try{
var resp = await http.get(url);
throw Exception();
}catch(e){
_showMyDialog(context); //add this too
}
}