Search code examples
flutterapirestdioflutter-http

Which is the best way of api call in flutter


I'm new in flutter development. Recently I heard about Dio and Http packages for api calling. Which is the best one for api calling. If anyone have a better way of api service??

  CreateAccountRepository.internal();

  static final CreateAccountRepository _singleInstance =
      CreateAccountRepository.internal();

  factory CreateAccountRepository() => _singleInstance;

  //api: Registration
  Future<CreateAccountResponse> userRegistration(
      AccountCreateRequest requestParams) async {
    bool isNetworkAvail = await NetworkCheck().check();
    if (isNetworkAvail) {
      final response = await networkProvider.call(
          method: Method.POST,
          pathUrl: AppUrl.pathRegister,
          body: requestParams.toJson(),
          headers: headerContentTypeAndAccept);
      if (response.statusCode == HttpStatus.ok) {
        String location = response.headers['location'];
        String userId = location.split("/").last;
        CreateAccountResponse createAccountResponse =
            CreateAccountResponse.fromJson(json.decode(response.body));
        createAccountResponse.isSuccess = true;
        createAccountResponse.userId = int.parse(userId);
        return createAccountResponse;
      } else if (response.statusCode == HttpStatus.unprocessableEntity) {
        return CreateAccountResponse.fromJson(json.decode(response.body));
      } else if (response.statusCode == HttpStatus.badRequest) {
        return CreateAccountResponse.fromJson(json.decode(response.body));
      } else {
        return CreateAccountResponse.fromJson(json.decode(response.body));
      }
    } else {
      return CreateAccountResponse(
          message: AppStrings.ERROR_INTERNET_CONNECTION);
    }
  }
}

Solution

  • dio and http is best. Now, I'm dio is used in

    Dio is a powerful HTTP client for Dart. It has support for interceptors, global configuration, FormData, request cancellation, file downloading, and timeout, among others. Flutter offers an http package that’s nice for performing basic network tasks but is pretty daunting to use when handling some advanced features. By comparison, Dio provides an intuitive API for performing advanced network tasks with ease.