Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
5.2k 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...