[flutter学习笔记] flutter 网络请求+json解析

知识点来自于下方链接,本文只是记录下编码时遇到的一些问题

(2条消息) Flutter基础(十一)网络请求(Dio)与JSON数据解析_BATcoder - 刘望舒-CSDN博客

总结:

  1. 网络请求使用dio,引用时需要在pubspec.yaml中dependencies节点下配置dio: ^4.0.0。

  2. json解析使用自带jsonDecode,json模板代码使用 quicktype 生成,这个网站非常好用。

  3. 在使用测试json地址(https://jsonplaceholder.typicode.com/posts)进行测试的时候,发现如果什么都不设置,请求后返回的response直接toString进行解析会出错,原因是dio默认的responseType为json,返回的response会吃掉引号导致解析报错,手动设置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 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 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 userFromJson(String str) =>
    List.from(json.decode(str).map((x) => User.fromJson(x)));

String userToJson(List data) =>
    json.encode(List.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 json) => User(
        userId: json["userId"],
        id: json["id"],
        title: json["title"],
        body: json["body"],
      );

  Map toJson() => {
        "userId": userId,
        "id": id,
        "title": title,
        "body": body,
      };
}

你可能感兴趣的:([flutter学习笔记] flutter 网络请求+json解析)