“This is the 17th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

In the process of project development, it is inevitable to send network requests to obtain data. Today we will explain how to send network requests in Flutter.

Network request

In Flutter, two libraries are used to send network requests:

  • HTTP (official)

  • dio

Today we’re going to use the official HTTP to send web requests;

Configure the network request library

Dev /packages/ht… , the webpage is as follows:

Click the button shown in the red box in the picture to copy:

As you can see, we copied a string:

http: ^0.134.
Copy the code

So, what does this string do? Open the project’s pubspec.yaml file and find the area shown in the red box:

Be careful not to find the wrong area;

We see that in the red box, cupertina_icons: ^1.0.2 is exactly the same as the HTTP: ^0.13.4 that we copied. Here are some of the libraries we need to use. We add the HTTP configuration information to it, similar to how CocoaPods is used in iOS:

Then click the Pub GET button as shown by the arrow in the picture. The console input the following information to indicate that the load is successful and we can use the HTTP library:

Use of the network request library

We’ve loaded HTTP successfully, so how do we use it? First, we need to introduce HTTP to the page that uses HTTP, with the following code:

import 'package:http/http.dart' as http;
Copy the code

We then define a method to request the data and call it in initState:

@override
void initState() {
  super.initState();
  // Send a network request
  getConversationList();
}

getConversationList() {

}
Copy the code

It is important to note that we are sending the network request in the getConversationList method, so it should obviously execute asynchronously and not affect the rest of the code, so we need to add an asynchronous flag to the getConversationList method:

getConversationList() async{}Copy the code

Sending HTTP requests

The next step is to relax network requests. HTTP sends network requests as follows:

It is important to note that get() is a relaxed network request with a get method defined as follows:

Future<Response> get(Uri url, {Map<String.String>? headers}) =>
    _withClient((client) => client.get(url, headers: headers));
Copy the code

As you can see, this method returns a value; When we are developing iOS projects, we send network requests, and the result data of the request is usually returned by block callback; In a Flutter HTTP request, the data method returns a value directly, and get() should obviously be an asynchronous request, so we need to await it:

Let’s print out the result of the network request:

Analytical data

Now that we’ve retrieved the data from the server, it’s time to parse the data:

List<Chat> chatList = responseBody['chat_list'].map<Chat>((item) => Chat.formMap(item)).toList();
Copy the code

This code means: Fetches the chat_list array from responseBody, and the map method iterates over the array as item, converting that item into Chat model data using chat. fromMap. Finally toList() means to put all converted chats into an array and return a List;

Let’s take a look at the print:

Asynchronous method return value

In iOS development, the data requested by a web Flutter is processed by a method and then released as a block. Can asynchronous methods receive the return value in Flutter? The answer is of course yes, we need to modify the method as follows:

Use the Future to receive the return value; This is a future data;

Let’s look at how the return value of the getConversationList method is handled:

You can also use chain calls:

getConversationList().then((value) {
	print('= = =$value');
});
Copy the code

Let’s have a look at the print:

Network request processing

We already know that network request data can be retrieved in THEN, so what other states can be handled?

  • Error handling

CatchError is used to catchError messages.

  • Request is completed

WhenComplete callback when the network request completes;

  • Setting timeout

timeoutYou can set the timeout period for network requests.

We set the timeout to 1 millisecond and look at the print:

We found that even if the network request times out, then and whenComplete callbacks are still executed. This is because there must be a result in Flutter even if the network request is issued, and the state of the result needs to be controlled by ourselves, for example, through a custom bool value:

Dio send request

Dio is the request framework of the development of the great god in China, we will talk about it in detail later; If you want to study it, you can go to DIO

Model transformation

Our network requests typically return data in JSON format, so what if we convert JSON strings into model data?

The Map to json

Importing header files:

import 'dart:convert';
Copy the code

After introducing header files, you can call the encode method transform directly using JSON;

The conversion from JSON to map is as follows:

final map = {'name': 'Joe'.'age': '30'.'nickName': 'Outlaw maniac'};final jsonStr = json.encode(map);
print('map: $map');
print('json: $jsonStr');
Copy the code
  • json: callers, which can be used directly after importing header files;
  • map:MapType data;
  • jsonStr: after conversionjsonThe string;

Print result:

Flutter: map: {name: zhang SAN, age:30, nickName: exoteric} flutter: json: {"name":"Zhang"."age":"30"."nickName":"Outlaw."}
Copy the code

Json to turn the Map

final newMap = json.decode(jsonStr);
print('new: $newMap');
Copy the code
  • jsonThe: caller can be used directly after importing the header file
  • jsonStr: Needs to be convertedjsonThe string;
  • newMap: after conversionMapType data;

Print result:

flutter: new: {name: zhang SAN, age:30, nickName: outlaw}Copy the code

Json transfer model

We first define a Chat model data in the following format:

class Chat {
  final String? name;
  final String? message;
  final String? avatar;
  Chat({this.name, this.message, this.avatar});

  factory Chat.formMap(Map map) {
    return Chat(
      name: map['name'],
      message: map['message'],
      avatar: map['avatar']); }}Copy the code
  • factory: factory construct, which can define the return value of the constructor;

The conversion mode is as follows:

final map = {'name': 'Joe'.'message': 'hello'.'avatar': 'https://randomuser.me/api/portraits/men/21.jpg'};final chat = Chat.formMap(map);
print('name:${chat.name}; avatar:${chat.avatar}; message:${chat.message}');
Copy the code

Print result:

Flutter: name: Zhang SAN; avatar:https://randomuser.me/api/portraits/men/21.jpg; Message: how do you do?
Copy the code