Reputation: 1301
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
Upvotes: 0
Views: 752
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:
toString()
in the PhotoModel
class and return the url
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