Can't Catching two awaits in dart/fluttter http module

87 Views Asked by At

Please help I have been searching for hours and found no solution. I want to get data from two APIs so I call the two methods that return future and then await for their return value so that I don't wait if one takes too long. When I try to handle two SocketException (no internet) from http.get() in the async function only one is handled and an exception occurs breaking the program the exception is Exception has occurred. _ClientSocketException (Failed host lookup: 'APIs BASE_URL') from io_cleint.dart

home_page.dart

  Future<void> setRandomImageAndFact() async {
    setState(() {
      json = imageBytes = null;
    });

    Future<Uint8List> bytesImageFuture = getRandomImage();
    Future<Map<String, dynamic>> decodedJsonFuture = getRandomFact();

    try{
      imageBytes = await bytesImageFuture;
      json = await decodedJsonFuture;
    } on SocketException {
      socketException = true;
    }

    setState(() {});
  }

images.dart

Future<Uint8List> getRandomImage() async {
  Uri url = Uri.https(BASE_URL, "cat");

  http.Response response;

  try {
    response = await http.get(url);
  } on SocketException {
    rethrow;
  }

  if (response.statusCode == 200) {
    return response.bodyBytes;
  }

  throw Exception("Could not get random image ${response.statusCode}");
}

facts.dart

Future<Map<String, dynamic>> getRandomFact() async {
  Uri url = Uri.https(BASE_URL, "facts/random");
  Future<http.Response> responseFuture = http.get(url);
  Future<List<String>> rejectedListFuture = loadPrefs(Mode.rejected.value);

  List<String> rejectedList = await rejectedListFuture;
  http.Response response;

  try {
    response = await responseFuture;
  } on SocketException {
    rethrow;
  }

  if (response.statusCode == 200) {
    Map<String, dynamic> decodedJson = jsonDecode(response.body);
    if (rejectedList.every((element) => element != decodedJson['_id'])) {
      return decodedJson;
    } else {
      return getRandomFact();
    }
  }

  throw Exception("Could not get random fact ${response.statusCode}");
}

I tried making each one of the two awaits in its separate try-catch block same exception, tried using Future.wait:

    Future.wait([
      getRandomImage(),
      getRandomFact(),
    ]).then((value) {
      imageBytes = value[0] as Uint8List;
      json = value[1] as Map<String, dynamic>;
    }).catchError((e) {
      socketException = true;
    });

same exception but from images.dart

1

There are 1 best solutions below

2
Bibek Saha On

instead of using then do this

void doMultipleApiCall()
{
  getRandomImage().then((value) {
    imageBytes = value;
  }).catchError((e) {
    socketException = true;
  });
  getRandomFact().then((value) {
    json = value;
  }).catchError((e) {
    socketException = true;
  });
}

or this

  void doApiCalls() async {
    try{
      final imageBytes = await getRandomImage();
      final json = await getRandomFact();
    } on Exception catch(error,stackTrace)
    {
      socketException = true;
    }
  }

to understand why and how it works check this video for reference : https://www.youtube.com/watch?v=_oxD0USaBlY