Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.6k views
in Technique[技术] by (71.8m points)

Flutter throws TimeoutException despite having try/catch while getting data from API

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use response.statusCode.

final response = await http.get(
      "https://www.xxxxx.com/api/students",
    );
 
    if (response.statusCode == 200) {
      if (this.mounted) {
        setState(() {
          var responseJson = json.decode(response.body);
        });
      }
    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()));
    } else {
    finishedLoading = true;
    Fluttertoast.showToast(
       msg: "Failure",
       toastLength: Toast.LENGTH_SHORT,
       gravity: ToastGravity.BOTTOM,
       timeInSecForIosWeb: 5,
       backgroundColor: Colors.green,
       textColor: Colors.white,
       fontSize: 14.0.sp);
    }

Try this code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...