Search code examples
flutterapidartexceptionsocketexception

How to create a screen on socket exception in flutter?


In my flutter project I need to show some illustration images when socket exception occurs when API was called. How can I do that ?

Thanks in advance


Solution

  • This will help on socket exception and format exception.

    Create model class for httpresponse

    class HTTPResponse<T> {
      bool isSuccessful;
      T data;
      String message;
      int responseCode;
      HTTPResponse(this.isSuccessful, this.data, {this.message, this.responseCode});
    }
    

    Then use this model in api response like this

    Future<HTTPResponse<List<Post>>> getPosts(
          {int limit = 20, int page = 1}) async {
        String url =
            'https://jsonplaceholder.typicode.com/posts?_limit=$limit&_page=$page';
        Uri uri = Uri.parse(url);
    
        try {
          var response = await http.get(uri);
          if (response.statusCode == 200) {
            var body = json.decode(response.body);
            List<Post> postsList = [];
            body.forEach((e) {
              Post post = Post.fromJson(e);
              postsList.add(post);
            });
            return HTTPResponse(
              true,
              postsList,
              responseCode: response.statusCode,
            );
          } else {
            return HTTPResponse(false, null,
                message: 'Invalid response from server',
                responseCode: response.statusCode);
          }
        } on SocketException {
          return HTTPResponse(false, [], message: 'Unable to reach the internet');
        } on FormatException {
          return HTTPResponse(false, [], message: 'Invalid response from server');
        } catch (e) {
          return HTTPResponse(false, [],
              message: "Something went wrong please try in a minute or two");
        }
      }