【问题标题】:How to get data from api in flutter where response is inside of list?如何在响应位于列表内的情况下从 api 获取数据?
【发布时间】:2022-11-02 14:16:47
【问题描述】:

下面给出的代码在我的响应中,我需要在 Listview 构建器中显示,现在我需要数据姓名在里面结果,我如何获取它并以文本形式显示它?

{
        "message": "sucess",
        "error": false,
        "code": 200,
        "result": [
            {
                "id": 1,
                "name": "Lab Report"
            },
            {
                "id": 2,
                "name": "News"
            },
            {
                "id": 3,
                "name": "X-ray"
            },
            {
                "id": 8,
                "name": "Blood Test"
            }
        ],
        "status": 200
    }

下面是我的响应模型类,现在我想要结果中的数据,需要在 Listview builder 中显示

import 'dart:convert';

PostFromJson postFromJsonFromJson(String str) => PostFromJson.fromJson(json.decode(str));

String postFromJsonToJson(PostFromJson data) => json.encode(data.toJson());

class PostFromJson {
  PostFromJson({
    this.message,
    this.error,
    this.code,
    required this.result,
    this.status,
  });

  String? message;
  bool? error;
  int? code;
  List<Result> result;
  int? status;

  factory PostFromJson.fromJson(Map<String, dynamic> json) => PostFromJson(
    message: json["message"],
    error: json["error"],
    code: json["code"],
    result: List<Result>.from(json["result"].map((x) => Result.fromJson(x))),
    status: json["status"],
  );

  Map<String, dynamic> toJson() => {
    "message": message,
    "error": error,
    "code": code,
    "result": List<dynamic>.from(result.map((x) => x.toJson())),
    "status": status,
  };
}

class Result {
  Result({
     this.id,
    this.name,
  });

  int? id;
  String? name;

  factory Result.fromJson(Map<String, dynamic> json) => Result(
    id: json["id"],
    name: json["name"],
  );

  Map<String, dynamic> toJson() => {
    "id": id,
    "name": name,
  };
}

【问题讨论】:

    标签: flutter api


    【解决方案1】:

    网上有很多关于如何获取数据、解析、建模和在 UI 中显示(来自 API)的资源。

    这是来自 Flutter 的一份官方文档:https://docs.flutter.dev/cookbook/networking/fetch-data

    【讨论】:

      【解决方案2】:

      最终名称 = 数据['结果'][0].name;

      最终 id = 数据['结果'][0].id;

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-09-09
        • 1970-01-01
        • 2020-08-14
        • 2019-10-06
        • 2020-11-11
        • 2013-09-08
        相关资源
        最近更新 更多