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
#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.
#3.Create Service 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:
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.
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.
#Enhance loading with Shimmer Effect: -Replace CircularProcessIndicator with Shimmer.fromColors()
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.