I have the following code to get data from API using Dio
:
_fetchData() async {
try {
Dio dio = new Dio();
list.clear();
final response = await dio
.get(
"http://"+ip+"/api/students",
cancelToken: token,
)
.timeout(Duration(seconds: 2), onTimeout: () {
token.cancel();
return;
});
list = json.decode(response.data) as List;
finishedLoading = true;
Fluttertoast.showToast(
msg: "Success",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 5,
backgroundColor: Colors.green,
textColor: Colors.white,
fontSize: 14.0.sp);
Navigator.push(
context, MaterialPageRoute(builder: (context) => Details()));
} on DioError catch (e) {
Fluttertoast.showToast(
msg: "Failure",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 5,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 14.0.sp);
}
}
What I'm trying to do is, show a toast instead of throwing an exception, what the code throws a TimeoutException after around 2 minutes of the execution of that method, I just want the application to show the toast that it couldn't connect to the API and not throw the exception afterwards.
Thanks for the help in advance.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…