This is the 30th day of my participation in the More Text Challenge. For more details, see more text Challenge

Dio is an open source plugin developed by Chinese people. It has received 99% reviews on Pub and nearly 10,000 stars on GitHub. Dio is a powerful Dart Http request library that supports Restful apis, FormData, interceptors, request cancellation, Cookie management, file upload/download, timeouts, custom adapters… It can be said to cover all the network requests involved.

preparation

When it comes to network requests, validating interface requests is a bit of a hassle. Just testing CRUD requests is fine and can be done using a tool like JsonPlaceholder (domestic access is a bit slow). If you want to build a full App, you need to have a back end. If you don’t understand the back end, you can only use the Mock tool. As a student who wants to be a full stack, how can you Mock it? GitHub walk a circle, found a based on express.js framework API source code, is a foreigner wrote, look at it, found that it is not too difficult to understand, rote copy change bai!

I have uploaded the background source, you can see, if you don’t want to see, configured environment directly according to the document, follow the orders under the directory node index. The js can start a local service, listening to the API address at: http://localhost:3900/api/. Want oneself to change, need to have the following knowledge (study hard, young!

  • MongoDB: The background database uses MongoDB, usingmongooseThe implementation of MongoDB access, basic MongoDB operations to be able to refer to my column:MongoDB is not professional.
  • Javascript: JS doesn’t work, so I’m sure you won’t, but Dart is similar to JS and won’t take much effort to learn.

Hello, dio

Dio is a very Chinese name (read it in pinyin, or maybe I’m mistaken, it’s an abbreviation of Dart IO). The latest version of DIO is currently 4.0.0. Let’s start with basic get, POST, PUT, patch, and DELETE requests. A get request

Response response;
var dio = Dio();
response = await dio.get('/test? id=12&name=wendu');
print(response.data.toString());
// You can also make a request using the query parameter
response = await dio.get('/test', queryParameters: {'id': 12.'name': 'wendu'});
print(response.data.toString());

Copy the code

A post request

response = await dio.post('/test', data: {'id': 12.'name': 'wendu'});
Copy the code

Patch and PUT requests

var result = await Dio().patch('/test/12', data: data);
var result = await Dio().put('/test/12', data: data);
Copy the code

The delete request

var result = await Dio().delete('/test/12');
Copy the code

The returned result will contain the HTTP request’s status code, information, header, and response data, with the response data in the data attribute.

A profound

The previous data was our Mock data, now modified to get it from the web, the interface is ready for: http://localhost:3900/api/dynamics, support the incoming paging parameters. For simplicity, only paging data is returned, not paging information. _ Note: You can run _**_node seed.js_**_ to generate database data in the background project directory. _

Add dio dependencies to pubspec.yaml:

dio: ^ 4.0.0
Copy the code

To avoid key subscript access to a utility Map, we prepare an entity class, DynamicEntity, to convert Map data into entity objects.

class DynamicEntity {
  String _title;
  String _imageUrl;
  int _viewCount;
  String _id;

  get title => _title;
  get imageUrl => _imageUrl;
  get viewCount => _viewCount;
  get id => _id;

  static DynamicEntity fromJson(Map<String.dynamic> json) {
    DynamicEntity newEntity = DynamicEntity();
    newEntity._id = json['_id'];
    newEntity._title = json['title'];
    newEntity._imageUrl = json['imageUrl'];
    newEntity._viewCount = json['viewCount'];

    returnnewEntity; }}Copy the code

Interface request class create an interface request class DynamicService, and put all dynamically involved network requests into this class. All the methods in it are defined as static methods, so as to avoid the need to instantiate objects to request. Currently, we only verify the list of interfaces, and there is no error and exception handling here.

import 'package:dio/dio.dart';

class DynamicService {
  static String host = 'http://localhost:3900/api/';
  static Future list(page, pageSize) async {
    var result = await Dio().get(
      host + 'dynamics',
      queryParameters: {'page': page, 'pageSize': pageSize},
    );

    returnresult; }}Copy the code

Change the original Mock data to a network request

Our previous Mock data is modeled after the API interface, so it is easy to change. Let’s compare the code:

// Use Mock data
void _requestNewItems() async {
    List<Map<String.dynamic>> _jsonItems =
        await DynamicMockData.list(_currentPage, PAGE_SIZE);
    List<DynamicEntity> _newItems =
        _jsonItems.map((json) => DynamicEntity.fromJson(json)).toList();
    this.setState(() {
      if (_currentPage > 1) {
        _listItems += _newItems;
      } else{ _listItems = _newItems; }}); }// After the network request
void _requestNewItems() async {
    var response = await DynamicService.list(_currentPage, PAGE_SIZE);
    List<dynamic> _jsonItems = response.data;
    List<DynamicEntity> _newItems =
        _jsonItems.map((json) => DynamicEntity.fromJson(json)).toList();
    this.setState(() {
      if (_currentPage > 1) {
        _listItems += _newItems;
      } else{ _listItems = _newItems; }}); }Copy the code

In actual development, you can have the Mock data class implement the same interface as the real interface class, so you can simply replace the implementation class of the interface, often referred to as interface-oriented programming.

run

When the modification is complete, run the code directly and you can see that the ID has changed.

conclusion

This brief introduction to DIO, and the fact that the GET request completes the acquisition of tabbed data, gives you a glimpse of how simple dio is to use. Additional requests and more advanced uses will follow to see the power of DIO.