Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use dio in Flutter

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

Today, the editor will share with you the relevant knowledge about how to use dio in Flutter. The content is detailed and the logic is clear. I believe most people still know too much about this, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

Initialize Dio

You can create a separate class that contains methods for performing network operations. This helps to separate functional logic from user interface code.

To do this, create a new file: dio_client.dart contains DioClient

Class DioClient {/ / TODO: Set up and define the methods for network operations}

You can initialize Dio using the following methods:

Import 'package:dio/dio.dart';class DioClient {final Dio _ dio = Dio ();}

Define the basic URL of the API server:

Import 'package:dio/dio.dart';class DioClient {final Dio _ dio = Dio (); final _ baseUrl =' https://reqres.in/api'; / / TODO: Add methods}

We can now define the methods needed to execute the network request.

Define GET request

We will define a method id that retrieves individual user data from API by passing it:

Future getUser ({required String id}) async {/ / Perform GET request to the endpoint "/ users/" Response userData = await _ dio.get (_ baseUrl +'/ users/$id'); / / Prints the raw data returned by the server print ('User Info: ${userData.data}'); / / Parsing the raw JSON data to the User class User user = User.fromJson (userData.data); return user;}

The above method works, but if there are any coding errors here, the application will crash while you are running.

A better and more practical method is to use block packaging method: get () ``try-catch

Future getUser ({required String id}) async {User? User; try {Response userData = await _ dio.get (_ baseUrl +'/ users/$id'); print ('User Info: ${userData.data}'); user = User.fromJson (userData.data);} on DioError catch (e) {/ / The request was made and the server responded with a status code / / that falls out of the range of 2xx and is also not 304. If (e.response! = null) {print ('Dio errorships'); print ('STATUS: ${e.response?.statusCode}'); print ('DATA: ${e.response?.data}'); print ('HEADERS: ${e.response?.headers}');} else {/ / Error due to setting up or sending the request print ('Error sending requests'); print (e.message) }} return user;}

In this example, we also set the User to be nullable so that if any errors occur, the server will return null instead of any actual user data.

In order to display user data, we must build the HomePage class. Create a new file called home_page.dart and add the following to it:

Class HomePage extends StatefulWidget {@ override _ HomePageState createState () = > _ HomePageState ();} class _ HomePageState extends State {final DioClient _ client = DioClient () @ override Widget build (BuildContext context) {return Scaffold (appBar: AppBar (title: Text ('User Info'),), body: Center (child: FutureBuilder (future: _ client.getUser (id:' 1'), builder: (context, snapshot) {if (snapshot.hasData) {User? UserInfo = snapshot.data; if (userInfo! = null) {Data userData = userInfo.data Return Column (mainAxisSize: MainAxisSize.min, children: [Image.network (userData.avatar), SizedBox (height: 8.0), Text ('${userInfo.data.firstName} ${userInfo.data.lastName}' Style: TextStyle (fontSize: 16.0), Text (userData.email, style: TextStyle (fontSize: 16.0),],) }} return CircularProgressIndicator ();},),);}}

Inside the _ HomePageState class, DioClient is instantiated first. Then, inside the build method, FutureBuilder is used to retrieve and display user data. It will be displayed when CircularProgressIndicator gets the result.

Define POST request

You can use POST requests to send data to API. Let's try to send a request and create a new user.

First, I will define another model class because the properties of this JSON data will be different from the User model class defined earlier and will be used to handle the user information that we have to send:

Import 'package:json_annotation/json_annotation.dart';part' user_info.g.dart';@JsonSerializable () class UserInfo {String name; String job; String? Id; String? CreatedAt; String? UpdatedAt; UserInfo ({required this.name, required this.job, this.id, this.createdAt, this.updatedAt,}); factory UserInfo.fromJson (Map json) = > _ $UserInfoFromJson (json); Map toJson () = > _ $UserInfoToJson (this);}

Specify the method used to create a new user in the DioClient class:

Future createUser ({required UserInfo userInfo}) async {UserInfo? RetrievedUser; try {Response response = await _ dio.post (_ baseUrl +'/ users', data: userInfo.toJson (),); print ('User created: ${response.data}'); retrievedUser = UserInfo.fromJson (response.data);} catch (e) {print ('Error creating user: $e');} return retrievedUser;}

This takes a UserInfo object as a parameter and sends it to the endpoint of the API. It returns a response with newly created user information and creation date and time. / users

Define PUT request

You can use PUT requests to update data that exists in the API server.

To define a new method DioClient in the class to update the user, we must pass the updated UserInfo object along with the user to which the id is applying the update.

Future updateUser ({required UserInfo userInfo, required String id,}) async {UserInfo? UpdatedUser; try {Response response = await _ dio.put (_ baseUrl +'/ users/$id', data: userInfo.toJson (),); print ('User updated: ${response.data}'); updatedUser = UserInfo.fromJson (response.data);} catch (e) {print ('Error updating user: $e');} return updatedUser;}

The above code sends an PUT request / users/ and UserInfo data to the endpoint. It then returns the updated user information as well as the date and time of the update.

Define DELETE request

You can use DELETE requests to delete some data from the server.

Define a new method in the DioClient class to remove the id user from the API server by passing the user's.

Future deleteUser ({required String id}) async {try {await _ dio.delete (_ baseUrl +'/ users/$id'); print ('User deleted');} catch (e) {print ('Error deleting user: $e');}}

Select and define your request header

BaseUrl you can define it internally BaseOptions and pass it once when instantiated instead of passing the endpoint Dio every time.

To do this, you need to initialize Dio as follows:

Final Dio _ dio = Dio (BaseOptions (baseUrl: 'https://reqres.in/api', connectTimeout: 5000, receiveTimeout: 3000,),)

This method also provides a variety of other customizations-- in the same example, we defined connectTimeout and receiveTimeout for the request.

Upload files

Dio makes it easier to upload files to the server. It can handle multiple file uploads at the same time, and has a simple callback to track their progress, which makes it easier to use than http packages.

You can easily upload files to the server using FormDataDio. The following is an example of sending an image file to API:

String imagePath;FormData formData = FormData.fromMap ({"image": await MultipartFile.fromFile (imagePath, filename: "upload.jpeg",),}); Response response = await _ dio.post ('/ search', data: formData, onSendProgress: (int sent, int total) {print ('$sent $total');},); interceptor

You can intercept then catchError before using them to process Dio requests and respond to errors. In real-world scenarios, interceptors can be used to use JSON Web Tokens (JWT) to authorize, parse JSON, handle errors, and easily debug Dio network requests.

You can run intercept: onRequest,onResponse, and onError by rewriting the callback.

For our example, we will define a simple interceptor to record different types of requests. Create a new class named Logging that extends from the following Interceptor:

Import 'package:dio/dio.dart';class Logging extends Interceptor {@ override void onRequest (RequestOptions options, RequestInterceptorHandler handler) {print (' REQUEST [${options.method}] = > PATH: ${options.path}'); return super.onRequest (options, handler);} @ override void onResponse (Response response, ResponseInterceptorHandler handler) {print ('RESPONSE [${response.statusCode}] = > PATH: ${response.requestOptions.path}',); return super.onResponse (response, handler) } @ override void onError (DioError err, ErrorInterceptorHandler handler) {print ('ERROR [${err.response?.statusCode}] = > PATH: ${err.requestOptions.path}',); return super.onError (err, handler);}}

Here, we cover the various callbacks triggered by the Dio request and add a print statement for each callback to record the request in the console.

Dio adds an interceptor during initialization:

Final Dio _ dio = Dio (BaseOptions (baseUrl: 'https://reqres.in/api', connectTimeout: 5000, receiveTimeout: 3000,),).. promotors.add (Logging ())

The results recorded in the debugging console will be as follows:

These are all the contents of the article "how to use dio in Flutter". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report