2

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);
    }
  }
}
kapil tk
  • 186
  • 10

4 Answers4

2

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.

Javatar
  • 131
  • 6
2

In Flutter, there are multiple ways to make API calls depending on the specific use case and requirements of your application. Three common ways to make API calls in Flutter:

HTTP: The http package is a popular package that provides a simple way to make HTTP requests in Flutter. You can use this package to make GET, POST, PUT, and DELETE requests.Example of GET request using the http package:

import 'package:http/http.dart' as http;
final response = await 
http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
if (response.statusCode == 200) {
  // Do something with the response data
} else {
 // Handle error
}

DIO: The dio package is another popular package for making HTTP requests in Flutter. It provides features such as request cancellation, file uploading, and request interception.Example of making a GET request using the dio package:

import 'package:dio/dio.dart';
final dio = Dio();
final response = await 
dio.get('https://jsonplaceholder.typicode.com/posts');
if (response.statusCode == 200) {
   // Do something with the response data
} else {
  // Handle error
}

State management: If you're using a state management library like Provider or Bloc, you can use that library to make API calls. This approach can help you separate the API logic from the UI logic and make it easier to test your code.Example of using Provider to make a GET request:

import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:http/http.dart' as http;

final postsProvider = FutureProvider<List<Post>>((ref) async {
final response = await 
http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
 if (response.statusCode == 200) {
  final List<dynamic> json = jsonDecode(response.body);
  return json.map((post) => Post.fromJson(post)).toList();
 } else {
    throw Exception('Failed to load posts');
 }
});

But I recommend you to use dio. Because it is easy to Use and It provides features such as request cancellation, file uploading, and request interception

Jatin Sharma
  • 146
  • 1
  • 11
1

Dio is generally considered to be faster and more efficient than http, due to its use of a dedicated HTTP client and support for asynchronous requests. Both packages have active and supportive communities, but Dio is generally more popular and has more contributors and resources available. I generlly prefer dio to be used for api's.

1

Both Dio and HTTP package are useful but if you are new or at the begging level you should use HTTP for the network call after the complex scenario or at the certain point you will need dio suppose you need request, connection and response timeout or else before request you pass some data and before response you add some extra functionality then Dio will helpful for you. You can refer Dio and HTTP package from official platform pub.dev.

AJJ
  • 46
  • 3