简体   繁体   English

从 API 获取数据时出现错误,如果出现抖动,我应该如何获取数据?

[英]I got an error while getting data from the API, how should I get the data if flutter?

I am getting data from an API using a model.我正在使用模型从API获取数据。 But I ran into a problem that when I get the 'gallery' data, I get an error, that is, I get the data incorrectly.但是我遇到了一个问题,当我获取'gallery'数据时,我得到一个错误,即我获取的数据不正确。 I need to get the 'gallery' field and inside it take the 'url' field - a link to the photo, in order to use it in the future.我需要获取'gallery'字段并在其中获取'url'字段 - 一个指向照片的链接,以便将来使用它。 Can you tell me how to get the 'url' field correctly?你能告诉我如何正确获取'url'字段吗?

{
    "data": {
        "id": 35,
        "picture_url": null,
        "email_confirmed": false,
        "gallery": [
            {
                "url": "https://picture-staging.s3.eu-central.jpeg",
                "mime_type": "image/jpeg",
                "type": "gallery",
                "updated_at": "2022",
                "created_at": "2022"
            }
        ],
        "updated_at": "2022",
        "created_at": "2022"
    }
}

model模型

class User {
  final int id;
  List? gallery;

  User({
    required this.id,
    this.gallery,
  });

  User.fromJson(Map<String, dynamic> json)
      : this(
          id: json['id'] as int,
          gallery: json['gallery']['url'],
        );

In your API response, there is a list of gallery objects therefore you have to traverse through all of them.在您的 API 响应中,有一个画廊对象列表,因此您必须遍历所有这些对象。

User.fromJson(Map<String, dynamic> json) {
    json = json['data'];
    id = json['id'];
    pictureUrl = json['picture_url'];
    emailConfirmed = json['email_confirmed'];
    if (json['gallery'] != null) {
      gallery = <Gallery>[];
      json['gallery'].forEach((v) {
        gallery!.add(new Gallery.fromJson(v));
      });
    }
    updatedAt = json['updated_at'];
    createdAt = json['created_at'];
  }

There are multiple tools that helps you create that .fromJson method, like this .有多种工具可以帮助您创建 .fromJson方法,例如 . Paste your json there and it will generate dart code for you, really helps me.将你的 json 粘贴到那里,它会为你生成 dart 代码,这对我很有帮助。

The usage should like this:用法应该是这样的:

User user = User.fromJson(yourApiResponseJson);
print(user.id);
print(user.gallery); //prints entire list of gallery
print(user.gallery.first.url); //prints only first object url

Hey you can use this tool to generate your dart model from json.嘿,您可以使用工具从 json 生成您的飞镖模型。

Below is generated code from above tool下面是从上面的工具生成的代码

// final user = userFromJson(jsonString);
import 'dart:convert';

User userFromJson(String str) => User.fromJson(json.decode(str));

String userToJson(User data) => json.encode(data.toJson());

class User {
  User({
    required this.data,
  });

  Data data;

  factory User.fromJson(Map<String, dynamic> json) => User(
    data: Data.fromJson(json["data"]),
  );

  Map<String, dynamic> toJson() => {
    "data": data.toJson(),
  };
}

class Data {
  Data({
    this.id,
    this.pictureUrl,
    this.emailConfirmed,
    this.gallery,
    this.updatedAt,
    this.createdAt,
  });

  int? id;
  String? pictureUrl;
  bool? emailConfirmed;
  List<Gallery>? gallery;
  String? updatedAt;
  String? createdAt;

  factory Data.fromJson(Map<String, dynamic> json) => Data(
    id: json["id"],
    pictureUrl: json["picture_url"],
    emailConfirmed: json["email_confirmed"],
    gallery: List<Gallery>.from(json["gallery"].map((x) => Gallery.fromJson(x))),
    updatedAt: json["updated_at"],
    createdAt: json["created_at"],
  );

  Map<String, dynamic> toJson() => {
    "id": id,
    "picture_url": pictureUrl,
    "email_confirmed": emailConfirmed,
    "gallery": List<dynamic>.from(gallery.map((x) => x.toJson())),
    "updated_at": updatedAt,
    "created_at": createdAt,
  };
}

class Gallery {
  Gallery({
    this.url,
    this.mimeType,
    this.type,
    this.updatedAt,
    this.createdAt,
  });

  String? url;
  String? mimeType;
  String? type;
  String? updatedAt;
  String? createdAt;

  factory Gallery.fromJson(Map<String, dynamic> json) => Gallery(
    url: json["url"],
    mimeType: json["mime_type"],
    type: json["type"],
    updatedAt: json["updated_at"],
    createdAt: json["created_at"],
  );

  Map<String, dynamic> toJson() => {
    "url": url,
    "mime_type": mimeType,
    "type": type,
    "updated_at": updatedAt,
    "created_at": createdAt,
  };
}

// You can use like this // 你可以这样使用

 final user = userFromJson(jsonString);
 String? url =  user.data?.gallery?.url;

I hope that is not your whole model, because that model is not accessing the "data" key on the json response, your model should start getting the key data then pass it to another class that in this case should be named User我希望这不是您的整个模型,因为该模型没有访问 json 响应上的"data"键,您的模型应该开始获取密钥data ,然后将其传递给另一个类,在这种情况下应该命名为User

here is a brief example这是一个简单的例子

class User {
    User({
        required this.data,
    });

    final Data data;

    factory User.fromJson(Map<String, dynamic> json) => User(
        data: Data.fromJson(json["data"]),
    );
}

The Data class could be like this: Data类可能是这样的:

class Data {
    Data({
        required this.id,
        required this.pictureUrl,
        required this.emailConfirmed,
        required this.gallery,
        required this.updatedAt,
        required this.createdAt,
    });

    final int id;
    final dynamic pictureUrl;
    final bool emailConfirmed;
    final List<Gallery> gallery;
    final String updatedAt;
    final String createdAt;

    factory Data.fromJson(Map<String, dynamic> json) => Data(
        id: json["id"],
        pictureUrl: json["picture_url"],
        emailConfirmed: json["email_confirmed"],
        gallery: List<Gallery>.from(json["gallery"].map((x) => Gallery.fromJson(x))),
        updatedAt: json["updated_at"],
        createdAt: json["created_at"],
    );
    
}

I reccomend you using Quicktype我推荐你使用Quicktype

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从 api 检索数据时出现此错误? - I got this error while retrieving data from the api? 如何通过从 flutter 中的一个 api 获取数据来获得这种按钮布局 - How can I get this kind of layout of buttons by getting data from one api in flutter 当我运行我的代码时,它会给出错误代码 400,但是当我进行热刷新时,它会在控制台中显示数据,同时从 flutter 中的 api 获取数据 - when i run my code it gives error code 400 but when i do hot refresh it shows data in console while getting data from api in flutter 将日期数据上传到 flutter 中的 firestore 时出现错误 - I am getting error while uploading date data to firestore in flutter 没有错误,但我在使用 GetX flutter 时没有从我的 Firestore 数据库中获取数据 - There's no error but I am not getting data from my firestore database while using GetX flutter 我在尝试将数据从云 Firestore 带到我的 flutter 应用程序时遇到此错误 - I am getting this error while am trying to bring data from cloud firestore to my flutter app 我在从laravel api获取数据时遇到问题(颤振) - i have an issue in getting data from laravel api (flutter) 使用 flutter 在实时数据库中显示相关下拉列表中的数据时出现错误 - I got an error while displaying data in dependent drop down in real time database using flutter Flutter:我正在尝试将 api 数据提取到列表视图中,出现错误“类型'字符串'不是'索引'类型'int'的子类型” - Flutter : I'm trying to fetch api data into listview , got that error “ type 'String' is not a subtype of type 'int' of 'index' ” 从本地托管的 ASP.net api 获取数据时,我的颤振代码中有错误 - i have errors in my flutter code while getting data from ASP.net api which is hosted locally
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM