[flutter學(xué)習(xí)筆記] flutter 網(wǎng)絡(luò)請求+json解析

知識點來自于下方鏈接,本文只是記錄下編碼時遇到的一些問題

(2條消息) Flutter基礎(chǔ)(十一)網(wǎng)絡(luò)請求(Dio)與JSON數(shù)據(jù)解析_BATcoder - 劉望舒-CSDN博客

總結(jié):

  1. 網(wǎng)絡(luò)請求使用dio,引用時需要在pubspec.yaml中dependencies節(jié)點下配置dio: ^4.0.0。

  2. json解析使用自帶jsonDecode,json模板代碼使用 quicktype 生成,這個網(wǎng)站非常好用。

  3. 在使用測試json地址(https://jsonplaceholder.typicode.com/posts)進(jìn)行測試的時候,發(fā)現(xiàn)如果什么都不設(shè)置,請求后返回的response直接toString進(jìn)行解析會出錯,原因是dio默認(rèn)的responseType為json,返回的response會吃掉引號導(dǎo)致解析報錯,手動設(shè)置responseType為plain即可正常解析。

具體的代碼如下:

import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class RequestTest extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new MyState();
  }
}

class MyState extends State {
  @override
  void initState() {
    super.initState();
    // loadData();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Center(
          child: new ElevatedButton(
              onPressed: loadData,
              style: new ButtonStyle(),
              child: new Text("start request!"))),
    );
  }

  loadData() async {
    String dataURL = "https://jsonplaceholder.typicode.com/posts";
    try {
      Response response =
          await Dio(BaseOptions(responseType: ResponseType.plain)).get(dataURL);
      print(
          "request complete ! code = ${response.statusCode}  message = ${response.statusMessage}");
      if (response.statusCode == 200) {
        List<User> users = userFromJson(response.data.toString());
        var firstUser = users[66];
        print(
            "parse success ---- userId = ${firstUser.userId} ,title = ${firstUser.title}");
      }
    } catch (e) {
      print('error happened  ${e.toString()}');
    }
  }
}

List<User> userFromJson(String str) =>
    List<User>.from(json.decode(str).map((x) => User.fromJson(x)));

String userToJson(List<User> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class User {
  User({
    this.userId,
    this.id,
    this.title,
    this.body,
  });

  int userId;
  int id;
  String title;
  String body;

  factory User.fromJson(Map<String, dynamic> json) => User(
        userId: json["userId"],
        id: json["id"],
        title: json["title"],
        body: json["body"],
      );

  Map<String, dynamic> toJson() => {
        "userId": userId,
        "id": id,
        "title": title,
        "body": body,
      };
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容