skip to Main Content

This is my API

Future<void> getItems(int id) async {
    final uri = Uri.parse('$kApiUrl${kApiUrlItems}P_ID=$id');
    http.Response response = await http.get(uri).timeout(kTimeoutDuration); //5 sec

    try {
      if (response.statusCode == 200) {
        //ok
      }
      else {
        await Fluttertoast.showToast(...);
      }
    }
    on SocketException catch (e) {
        await Fluttertoast.showToast(...);
    } on TimeoutException catch (e) {
        await Fluttertoast.showToast(...);
    } catch (e) {
        await Fluttertoast.showToast(...);
    }
  }

When disable WIFI and Mobile data on emulator got error in console eg. Unhandled Exception: Failed host lookup:

Is it possible catch this error and show in Fluttertoast or snackbar?

I’m added SocketException, TimeoutException and catch but don’t get error within them!

2

Answers


  1. You can try wrap final uri and response in try like this:

    Future<void> getItems(int id) async {
        try {
          final uri = Uri.parse('$kApiUrl${kApiUrlItems}P_ID=$id');
          http.Response response = await http.get(uri).timeout(kTimeoutDuration); //5 sec
        
          if (response.statusCode == 200) {
            //ok
          }
          else {
            await Fluttertoast.showToast(...);
          }
        }
        on SocketException catch (e) {
            await Fluttertoast.showToast(...);
        } on TimeoutException catch (e) {
            await Fluttertoast.showToast(...);
        } catch (e) {
            await Fluttertoast.showToast(...);
        }
      }
    
    Login or Signup to reply.
  2. I think you need to check the internet connection first before sending the API You can check it using this https://pub.dev/packages/connectivity_plus
    after installing this update your project like this

    Future<bool> checkInternetConnection() async {
      var connectivityResult = await (Connectivity().checkConnectivity());
      if (connectivityResult == ConnectivityResult.none) {
        return false;
      } else {
        return true;
      }
    }
    
    Future<void> getItems(int id) async {
    if(checkInternetConnection()){
        try {
          final uri = Uri.parse('$kApiUrl${kApiUrlItems}P_ID=$id');
          http.Response response = await http.get(uri).timeout(kTimeoutDuration); //5 sec
        
          if (response.statusCode == 200) {
            //ok
          }
          else {
            await Fluttertoast.showToast(...);
          }
        }
        on SocketException catch (e) {
            await Fluttertoast.showToast(...);
        } on TimeoutException catch (e) {
            await Fluttertoast.showToast(...);
        } catch (e) {
            await Fluttertoast.showToast(...);
        }}else{
    //show toast to turn on wifi or data
        }
          }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search