I am confused about the use of Lists in Flutter/Dart.
I have a model class called PostMedia:
class PostMedia {
String media_url;
bool es_foto;
bool es_video;
bool es_youtube;
PostMedia({this.media_url, this.es_foto, this.es_video, this.es_youtube});
factory PostMedia.fromJson(Map<String, dynamic> json) => PostMedia(
media_url: json['media_url'],
es_foto: json['es_foto'],
es_video: json['es_video'],
es_youtube: json['es_youtube']);
Map<String, dynamic> toJson() => {
"media_url": media_url,
"es_foto": es_foto,
"es_video": es_video,
"es_youtube": es_youtube
};
}
On an app screen I am getting Firestore documents. Each document has a boolean field called post_tiene_fotos and string fields for media url, like foto1, foto2, foto3, etc:
foto1= "https://mipagina.es/foto1r3424.jpg
foto2= "https://mipagina.es/foto5453535.jpg
foto3= "https://mipagina.es/foto98989.jpg
I am passing all Firestore docunents to a list of type Post called listraFiltrada
.
Then I would like to create a PostMedia List to show the media files on a PageView widget that requires a List of type PostMedia to show the media files.
I would like to add each foto1, foto2 and foto3 url and media type to a List called lista_medios as follows:
ListView.builder(
itemCount: listaFiltrada.length,
itemBuilder: (context, index) {
bool es_ambassador =
listaFiltrada[index].post_autor_is_ambassador;
//ver si el post tiene media
bool tiene_media =
listaFiltrada[index].post_tiene_media;
bool tiene_fotos =
listaFiltrada[index].post_tiene_fotos;
List<PostMedia> lista_medios;
lista_medios = [];
if (tiene_fotos) {
//foto 1
var foto1 = listaFiltrada[index].foto_1;
//incluimos foto1 en la lista
List<PostMedia> lista = [
PostMedia(
media_url: foto1,
es_foto: true,
es_video: false,
es_youtube: false)
];
lista_medios.add(lista);
But I am getting the warning:
The argument type 'List<PostMedia>' can't be assigned to the parameter type 'PostMedia/
Which is the proper way to get the value for foto1, convert it to an element of type PostMedia, and then how to add more elements like foto2 and foto3?
CodePudding user response:
You are actually inserting List instead of PostMedia in lista_medois in the following line:
lista_medios.add(lista);
as lista
is also List<PostMedia>
.
either try converting List<PostMedia> lista_medios;
to List<List<PostMedia>> lista_medios;
or choose appropriate data type according to your requirements.