I've internet turned off my phone to trigger a SocketException error. I make my api call and at the top of the stack the error can be seen on my debugger just before the await call. I want to handle this error at the UI layer. And at the bottom of my call stack I see the method getData . My understanding is: I can wrap this in a try/catch and handle the exception. But I can't seem to grab the error.. Here is the method:
Future<String> getData(String query) async {
try {
List<Suburb> suburbs = await model.getSuburbs('au', query);
if (suburbs.length == 1) {
suburbCode = suburbs[0].code;
isButtonDisabled = false;
return suburbs[0].name;
}
return showDialog<String>(
barrierDismissible: false,
context: context,
builder: (context) => SimpleDialog(
backgroundColor: Colors.black,
title: Text('Please choose your Suburb:'),
children: suburbs
.map((suburb) => SimpleDialogOption(
child: Text(suburb.name),
onPressed: () {
suburbCode = suburb.code;
isButtonDisabled = false;
Navigator.of(context).pop(suburb.name);
}))
.toList(),
));
} on SocketException catch (e) {
print(e);
}
}
The line List<Suburb> suburbs = await model.getSuburbs('au', query); is where I make the api call and where the debugger points to. But I can't seem to 'get in to the catch block'
on SocketException catch (e) {should work. Try to add this block within getSuburbs() and check. In one of my code, I catch socket exception where the API call is made [so insidegetSuburbs()] in your context) and throw a generic exception (via enum) from the caller [i.e.getData()]