Skip to content

diwasche/flutter-fetch-api-with-dio

 
 

Repository files navigation

flutter_fetch_api_with_dio


fetch-api-with-dio

Flutter fetch API with Dio Package Dio is a powerful Http client, which supports Interceptors, Global configuration, FormData, Request Cancellation, File downloading, Timeout etc. Check Out Example to Fetch API with Dio Package Pagination is ignored: I will cover it in next article API:https://reqres.in/api/users?page api

#1. Add Dio package Run this command: With Dart: $ dart pub add dio With Flutter: $ flutter pub add dio This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get): dependencies: dio: ^4.0.6


#2.Create an Model class First, create an UserModel class that contains the data from the network request. It includes a factory constructor that creates an UserModel from JSON.

model class


#3.Create Service dioclient Fetching data from the internet takes some time so make getUser() an asynchronous function. -The dio.get() function requests JSON data from the server. The JSON response data is stored in the response variable. Create instance of Dio with an optional BaseOptions object: dio2

Here within BaseOtiopns() We can define -baseUrl -connectTimeout

  • headers etc And API path is defined in get(path) We can observe that we don't need to Decode unlike Http package HTTP with decode-We store response.data in variable and convert it into a UserModel using the fromMap() factory method otherwise we throwing Exception. dio refactor

Refactor: It's better to create separate class for: -Handle Response-ApiClient -Convert response to Model-Repository This helps to easily track error and reuse. refactor1 refactor2


#4.UI home homeui


#Enhance loading with Shimmer Effect: -Replace CircularProcessIndicator with Shimmer.fromColors() shimmer shimmer

I hope this exposition hopefully demystified the use of Dio(Get method) to fetch API. Thanks for reading and see you in the next one.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • C++ 43.0%
  • CMake 37.3%
  • Dart 10.2%
  • HTML 3.8%
  • C 2.9%
  • Swift 2.4%
  • Other 0.4%