It was first posted on my official account

Message passing in Flutter

preface

Web request to data parsing is one of the essential processes of flutter. The official website of Flutter mainly introduces its own Http request +Json parsing, but also recommends better ways to combine web request to DIO and jSON_serializable. This article mainly introduces the use of these two methods, source code at the end

In this paper, an update to my gitpage xsfelvis. Making. IO / 2018/12/08 /…

dio

Introduction to the

Package address pub. Flutter – IO. Cn/packages/di… , adding dependencies

Dependencies: dio: ^ 1.0.9

Performing a GET Request support Restful APIS, FormData, interceptors, request cancellation, Cookie management, file upload/download, timeout, etc

Response response;
response=await dio.get("/test? id=12&name=wendu")
print(response.data.toString());
// Optionally the request above could also be done as
response=await dio.get("/test",data:{"id":12."name":"wendu"})
print(response.data.toString());
Copy the code

Performing a POST request:

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

Performing multiple concurrent requests:

response= await Future.wait([dio.post("/info"),dio.get("/token")]);
Copy the code

Downloading a file:

response=await dio.download("https://www.google.cn/"."./xx.html")
Copy the code

Sending FormData:

FormData formData = new FormData.from({
   "name": "wendux"."age": 25}); response = await dio.post("/info", data: formData)
Copy the code

Uploading multiple files to server by FormData:

FormData formData = new FormData.from({
   "name": "wendux"."age": 25."file1": new UploadFileInfo(new File("./upload.txt"), "upload1.txt"),
   // upload with bytes (List<int>) 
   "file2": new UploadFileInfo.fromBytes(utf8.encode("hello world"),"word.txt"),
   // Pass multiple files within an Array 
   "files": [
      new UploadFileInfo(new File("./example/upload.txt"), "upload.txt"),
      new UploadFileInfo(new File("./example/upload.txt"), "upload.txt")]}); response = await dio.post("/info", data: formData)
Copy the code

For more information, please refer to the author’s explanatory articles and examples

And since the native HTTP library of Flutter does not support Charles packet capture, the library can use a setup proxy to capture packets, replacing the IP address itself

dio.onHttpClientCreate = (HttpClient client) {
  client.findProxy = (uri) {
    //proxy all request to localhost:8888
    return "PROXY yourIP:yourPort";
  };
};
Copy the code

So you can catch the bag.

Network request encapsulation

Simple encapsulation makes us easier to use, the core code is as follows

void _request(String url, Function callBack, {String method, Map
       
         params, Function errorCallBack})
       ,> async {
// dio.onHttpClientCreate = (HttpClient client) {
// client.findProxy = (uri) {
// //proxy all request to localhost:8888
/ / return "PROXY 172.23.235.153:8888";
/ /};
/ /};
    String errorMsg = "";
    int statusCode;
    try {
      Response response;
      if (method == GET) {
        if(params ! =null && params.isNotEmpty) {
          StringBuffer sb = new StringBuffer("?");
          params.forEach((key, value) {
            sb.write("$key" + "=" + "$value" + "&");
          });
          String paramStr = sb.toString();
          paramStr = paramStr.substring(0, paramStr.length - 1);
          url += paramStr;
        }
        response = await dio.get(url);
      } else if (method == POST) {
        if(params ! =null && params.isNotEmpty) {
          response = await dio.post(url, data: params);
        } else {
          response = await dio.post(url);
        }
      }

      statusCode = response.statusCode;
      if (statusCode < 0) {
        errorMsg = Network request error, status code: + statusCode.toString();
        _handError(errorCallBack, errorMsg);
        return;
      }
      if(callBack ! =null) {
        String res2Json  = json.encode(response.data);
        Map<String,dynamic> map=json.decode(res2Json);
        callBack(map["data"]); }}catch(exception) { _handError(errorCallBack, exception.toString()); }}Copy the code

Detailed can refer to the source github.com/xsfelvis/le…

Use the following

HttpCore.instance.get(Api.HOME_BANNER, (data) {
  List<BannerData> banners = getBannersList(data);
  setState(() {
    slideData = banners;
  });
}, errorCallBack: (errorMsg) {
  print("error:" + errorMsg);
  return null;
});
Copy the code

pit

Response. data[‘data’] [‘data’] [‘data’] [‘data’] [‘data’] [‘data’] [‘data’] [‘data’] [‘data’] The reason is that this is not a JSON data, there is no double quoted false JSON data, but in jsonObject can, solve the following

if(callBack ! =null) {
  String res2Json  = json.encode(response.data);
  Map<String,dynamic> map=json.decode(res2Json);
  callBack(map["data"]);
}
Copy the code

json_serializable

Introduction to the

Package address pub. Flutter – IO. Cn/packages/js… Add the dependent

Dependencies: json_serializable: ^2.0.0 dev_dependencies build_runner: ^1.1.2 json_serializable: ^2.0.0

This is a good thing, the previous equivalent of json data is solved one by one through the key (for the built-in JSON parsing can see juejin.cn/post/684490…). Json_serializable allows us to deserialize directly into objects using tools similar to Gson, and also provides a tool to automatically help us generate code that is simple, fast and error-free

use

Take the following JSON as an example

{
    "data": {"curPage":2."datas":[
            {
                "apkLink":""."author":"Hong ocean"."chapterId":410."chapterName":"Yugang said."."collect":false."courseId":13."desc":""."envelopePic":""."fresh":false."id":7604."link":"https://mp.weixin.qq.com/s/cCZKmqKrdCn63eWTbOuANw"."niceDate":"2018-12-03"."origin":""."projectLink":""."publishTime":1543830090000."superChapterId":408."superChapterName":"Public Account"."tags":[
                    {
                        "name":"Public Account"."url":"/wxarticle/list/410/1"}]."title":"Use network caching in Retrofit and OkHttp for efficient access"."type":0."userId":- 1."visible":1."zan":0
            },
            {
                "apkLink":""."author":"Hong ocean"."chapterId":408."chapterName":"Hong ocean"."collect":false."courseId":13."desc":""."envelopePic":""."fresh":false."id":7605."link":"https://mp.weixin.qq.com/s/r3AWeYafyMEc1-g8BWEHBg"."niceDate":"2018-12-03"."origin":""."projectLink":""."publishTime":1543766400000."superChapterId":408."superChapterName":"Public Account"."tags":[
                    {
                        "name":"Public Account"."url":"/wxarticle/list/408/1"}]."title":"Can a non-UI thread call view.invalidate ()?"."type":0."userId":- 1."visible":1."zan":0}]."offset":20."over":false."pageCount":289."size":20."total":5779
    },
    "errorCode":0."errorMsg":""
}
Copy the code

For example, we first find the actual data information, because the processing of the different ErrorCode has been handled in the encapsulation network request above, we need to pay attention to the data in the actual content sender “data”, add the jsonObject in the above data, Copy the data key with curly braces to the code generator page above, as shown in the screenshot below

Then run flutter Packages pub run build_runner build under the current project directory

Then you get the news.g.art file

Then we can get the fields we care about directly by getting the object properties in use

// Get News data
void _getNewsList(int curpage) {
  var url = Api.HOME_ARTICLE + curpage.toString() + "/json";
  HttpCore.instance.get(url, (data) {
    News news = News.fromJson(data);
    List<Datas> newsDatas = news.datas;
    setState(() {
      listData = newsDatas;
    });
  });
}
Copy the code

other

Custom field handling

We can annotate and customize individual fields with JsonKey custom parameters. For example, whether to allow empty fields. Note that the absence of any JsonKey allows an empty JSON field by default. For example, parsed fields have a dash, whereas DART allows only alphanumeric underscores as variable names. So we have to give it special treatment. @jsonkey (name=”off-set”) to parse the map, usually a tool that generates code automatically

@JsonKey(name: 'off-set')
int offset;
Copy the code

practice

The effect is shown below.

Interface from the open interface to play Android

Code in Learnflutter demo3

Welcome to pay attention to my public number, learn together, improve together ~Copy the code