Home > Blockchain >  I got an error while getting data from the API, how should I get the data if flutter?
I got an error while getting data from the API, how should I get the data if flutter?

Time:06-25

I am getting data from an API using a model. But I ran into a problem that when I get the 'gallery' data, I get an error, that is, I get the data incorrectly. 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. Can you tell me how to get the 'url' field correctly?

{
    "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'],
        );

CodePudding user response:

In your API response, there is a list of gallery objects therefore you have to traverse through all of them.

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. Paste your json there and it will generate dart code for you, really helps me.

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

CodePudding user response:

Hey you can use this tool to generate your dart model from 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;

CodePudding user response:

I hope that is not your whole model, because that model is not accessing the "data" key o 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

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:

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

  • Related