Flutter encapsulated in a single request and a network library Example

https://zhuanlan.zhihu.com/p/53498914


Flutter encapsulated in a single request and a network library Example

 

 

Flutter encapsulated in a single request and a network library Example

 

Why? Why do we need a single case

In Android we often use OkHttp to network requests, but we do not always want to create a OkHttpClient; or will some initialization resources is very troublesome, consumption performance, we hope to create once, use everywhere. This time we need a single case. Dio as flutter in OkHttp, we can also be encapsulated with a singleton.

How? How to achieve a singleton with dart

Singleton generally several features:

  1. Behind class constructor
  2. It provides a method to obtain an instance of the class (Java is often a static method, the DCL or the like inside the static method, returns an instance)
  3. The instance can only be created once, only a memory, to get anywhere by calling feature in the method of Example 2 should be the same

Take a look at how to achieve Singleton pattern when "Dart Cookbook":

/*The singleton example shows how to do this 
(substitute your singleton class name for Immortal).
Use a factory constructor to implement the
 singleton pattern, as shown in the following code:*/
 class Immortal { static final Immortal theOne = new Immortal._internal('Connor MacLeod'); String name; factory Immortal(name) => theOne; // private, named constructor  Immortal._internal(this.name); } main() { var im1 = new Immortal('Juan Ramirez'); var im2 = new Immortal('The Kurgan'); print(im1.name); print(im2.name); print(Immortal.theOne.name); assert(identical(im1, im2)); }

You can see that he _internal () hides the construction method by private named constructor, provides a factory method to get an instance of the class, and with static final modification of the theOne, theOne will be initialized at compile time to ensure that the feature 3. As for why theOne initialized at compile time, reference  Static variable the Initialization the Opened up to the any expression The .

Singleton In Action! Singleton in the project

Dio is provided by a network request flutterchina library, it can be said Flutter in OkHttp, interceptors, cache and other features. DETAILED Reference Dio GitHub . I use a singleton in the project library with a layer of Dio simple package:

import "package:dio/dio.dart"; import 'dart:async';  class HttpUtil {  static final HttpUtil _instance = HttpUtil._internal();  Dio _client;   factory HttpUtil() => _instance;   HttpUtil._internal() {  if (null == _client) {  Options options = new Options();  options.baseUrl = "http://www.wanandroid.com";  options.receiveTimeout = 1000 * 10; //10秒  options.connectTimeout = 5000; //5秒  _client = new Dio(options); } } Future<Map<String, dynamic>> get(String path, [Map<String, dynamic> params]) async { Response<Map<String, dynamic>> response; if (null != params) { response = await _client.get(path, data: params); } else { response = await _client.get(path); } return response.data; } //...省略post等方法... }

One More Thing

App backend interface returns the data format generally have a fixed structure, to wanandroid.com development Api example:

{
  "data": {
    "curPage": 1, "datas": [], "offset": 0, "over": true, "pageCount": 0, "size": 20, "total": 0 }, "errorCode": 0, "errorMsg": "" }

To resolve this json, Android can play out the flowers. But flutter disable reflection, there is no such a library similar to Java in Gson. Internet provides a flutter in several ways json automatically generated according to the model, as follows:

Since the data in the project, fixed structure, the way I used paradigm + online tools to achieve resolve my json project, this approach may seem awkward (some students may wish to provide a more elegant way to let me learn at) :

1. Define an abstract class, conventional acts datas field model of:

abstract class JsonData{
  JsonData fromJson(Map<String, dynamic> json,JsonData mySelf); }

2. The data fields corresponding abstract model:

import 'package:flutter_app/bean/JsonData.dart'; import 'package:meta/meta.dart'; class PageData<T extends JsonData>{ List<T> datas; int curPage; int pageCount; //...省略size,total等字段  PageData.fromJson({@required Map<String, dynamic> json,@required JsonDataCreator beanCreator}) { // TODO: implement fromJson  curPage = json['curPage']; pageCount = json['pageCount']; print(json); if (json['datas'] != null) { datas = new List<T>(); json['datas'].forEach((v) { JsonData item = beanCreator(); item.fromJson(v,item); datas.add(item); }); } } } typedef JsonDataCreator = JsonData Function();

3. The abstract corresponding to the entire return results model:

import 'package:flutter_app/bean/PageData.dart'; import 'package:flutter_app/bean/JsonData.dart'; import 'package:meta/meta.dart'; class BaseResult<T extends JsonData>{ int errorCode; String errorMsg; PageData<T> data; BaseResult.fromJson({@required Map<String, dynamic> json,@required JsonDataCreator beanCreator}) { // TODO: implement fromJson  errorCode = json['errorCode']; errorMsg = json['errorMsg']; data = PageData.fromJson(json:json['data'],beanCreator: beanCreator); } } 

4. When used in the project, to get json, put online tools generated model, copy it, to change more than the agreed format. To wanandroid list of articles interfaces , for example, returns the following results:

{
  "data": {
    "curPage": 2, "datas": [ { "apkLink": "", "author": "鸿洋", "chapterId": 408, "chapterName": "鸿洋", "collect": false, "courseId": 13, "desc": "", "envelopePic": "", ...其他字段 "title": "一篇文本跳动控件,为你打开一扇大门,学会这两点心得,控件你也会写", "type": 0, "userId": -1, "visible": 1, "zan": 0 }, .... ], "errorCode":0, "errorMsg": } } 

A model corresponding to a package of data datas:

import 'package:flutter_app/bean/JsonData.dart'; class ProjectBean extends JsonData{ String title; String envelopePic; @override JsonData fromJson(Map<String, dynamic> json, JsonData mySelf) { // TODO: implement fromJson  if(mySelf is ProjectBean){ mySelf.title = json['title']; mySelf.envelopePic = json['envelopePic']; //...省略其他字段  } return mySelf; } } 

Request data, and analysis:

class ApiService{
  static Future<List<ProjectBean>> getProjectList() async{ String url = "/project/list/1/json"; Map<String,dynamic> response = await HttpUtil().get(url); BaseResult result = BaseResult<ProjectBean>.fromJson(json: response,beanCreator: ()=>ProjectBean()); print(result.data.datas.length); return result.data.datas; } } 

Because the flutter can not use reflection, I do not know of any way to obtain the actual type of paradigm, so PageData constructor fromJson () need to pass a closure to create a model.

Thanks

Thank these authors share knowledge, let me learn the process of reference data are available:

Help you organize a quick start Flutter Cheats mp.weixin.qq.comicon 8 articles, then you can not learn Flutter to hit me! mp.weixin.qq.comicon Flutter basis of free video tutorials total of 25 episodes completed juejin.im "Flutter real" open source eBook - Denver juejin.im

 

 

Guess you like

Origin www.cnblogs.com/sundaysme/p/12588716.html