Max
Max

Reputation: 1301

How to display the value of a variable from an model?

I make an API request and get data. I have created models in which the received values are stored. I'm using the gallery variable to store a list of photo links. Tell me, how can I access an element from this list of the gallery variable in order to display a photo by link?

model

class User {
  final int id;
  final List<PhotoModel>? gallery;

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

  factory User.fromJson(Map<String, dynamic> json) {
    List<PhotoModel> ph = [];
    json['gallery'].forEach((v) {
      ph.add(PhotoModel.fromJson(v));
    });

    return User(
      id: json['id'] as int,
      gallery: ph,
    );
  }
}

model2

class PhotoModel {
  final String url;

  PhotoModel({required this.url});

  factory PhotoModel.fromJson(Map<String, dynamic> json) {
    return PhotoModel(
      url: json['url'],
    );
  }
}

Here is what I get

enter image description here

Upvotes: 0

Views: 752

Answers (1)

Dimitrios Begnis
Dimitrios Begnis

Reputation: 813

You print out user.gallary which is a list of PhotoModel instances. So your output makes sense it seems so that your gallery contains one PhotoModel.

If you want a specific output for each PhotoModel you have several options:

  1. Override the toString() in the PhotoModel class and return the url
  2. Change your print statement so it directly prints the url instead of the object itself. print(widget.state.user!.gallery.map((p) => p.url));

Another alternative is to add an toJson() method to your class which works the other way around like fromJson() and returns a map. If you call this method and print the map every attribute of the model will be visible.

Upvotes: 1

Related Questions