Simplify api call from flutter with better error handling with this generic function and Either (Dartz)

Posted on : April 14, 2021

I am a huge fan of handling error's with Either<error,value> introduced by Dartz package because it really gives you a nice way handle errors in a sensible way.

If you don't understand what I'm talking about, you can checkout reso coders tutorial. So I'm not here to talk teach you again how to do it, but to show you a simple trick that really simplifies the process. Because when you need to heavyly rely on api calls and handling error this way sometimes will make you tiredsome because you'll found everytime you'll have to write almost same code repetetively again and again.

So what do I do?

I create a single generic function (whatever named), then I take !toJson and endpoint as function parameter because almost all the api call has the same baseUrl that I can get from somewhere else.

 Future<Either<ValueFailure, T>> _apiHandler<T>(
      { T Function(Map<String, dynamic> json) toJson,
       String endPoint}) async {
    final String baseUrl = getBaseUrl();
    final String token = getToken();

    final Map<String, String> _header = header;
    _header.addAll({"Authorization": "Bearer $token"});
    try {
      final http.Response _response =
          await http.get(Uri.parse("$baseUrl$endPoint"), headers: _header);

      if (_response.statusCode == 200) {
        final Map<String, dynamic> _regResponse =
            jsonDecode(_response.body) as Map<String, dynamic>;

        final T _typedResponse = toJson(_regResponse);
        return right(_typedResponse);
      } else {
        Logger().e(_response.body);
        return left(ValueFailure(errorMsg: _response.body));
      }
    } catch (e) {
      Logger().e(e);
      return left(ValueFailure(errorMsg: e.toString()));
    }
  }

Then call the function like this:

  Future<Either<ValueFailure, Value>> getApiResponseOrError() async {
    final Either<ValueFailure, Value> output = await _apiHandler(
        toJson: (json) => Value.fromJson(json),
        endPoint: '/someEndPoint');

    return output;
  }

See ? as simple as that, that's one time hassle and life time peace. hehe. I hope this simple trick will save you a lot of time and effor in writing good code, thank you so much and have a good day.


SquadHead.

Made with ❤ by Kousik.