EmJeiEn
EmJeiEn

Reputation: 1443

Flutter new Image.network foreach in ListView

I'm totally new to Flutter and Java based languages in general, coming from PHP background myself. This is going to be a very beginner question:

I'm creating a new Network.image via ListView like this:

new Image.network(snapshot.data[index].imageurl.toString() ?? ''),

ok, works great as the snapshot.data[index].imageurl is taken as:

data ['content'][0]['imageurl']

and defined as:

String imageurl;

However what I'd like to do is to take the whole array:

 data ['content']['imageurl']

which I suppose should be defined as:

List imageurl;

and loop through it to create own Image.network for each entry in array.

I have tried multiple things, including:

return new Column(
crossAxisAlignment: CrossAxisAlignment.start,
   children: <Widget>[
      snapshot.data[index].imageurl.forEach((data) {
        new Image.network(snapshot.data[index].imageurl.toString() ?? ''),
}

But foreEach loop is giving me an error:

"The expression here has a type of 'void', and therefore cannot be used.

How can I actually achieve this? Out of ideas here.

Upvotes: 2

Views: 3657

Answers (3)

Ayaz Nazir
Ayaz Nazir

Reputation: 81

ListView(
    children: snapshot.data.docs.map((DocumentSnapshot document) {
          return Padding(
          padding: const EdgeInsets.all(8.0),
          child: Container(
                  height: 500.h,
                  width: screenSized.width,
                  decoration: BoxDecoration(
                  image: DecorationImage(
                  image:NetworkImage(
                   document["userImage"]),
                  fit: BoxFit.cover
                  ),
                ),
             ),
           );
         }).toList(),
        );

Upvotes: 0

EmJeiEn
EmJeiEn

Reputation: 1443

Ok, so I finally figured it out.

List<Widget> result = content.map((c) => Image.network(snapshot.data[index].imageUrl.toString())).toList();

And to get the output the result I did return new Column:

children: result,

Upvotes: 2

Jonah Williams
Jonah Williams

Reputation: 21451

Iterable.forEach is for calling a function on every item of an Iterable. It doesn't produce any output (returning void), and anything returned from the provided function is discarded.

To produce a new List from an existing List or Iterable, you'll want to use the Iterable.map method.

For example:

List<Widget> result = snapshot.data[index].imageurl.map((data) {
  // Make sure to return the result.
  return Image.network(snapshot.data[index].imageurl.toString())
}).toList(); // Call to convert the Iterable into a List.

There is another potential issue: x.toString() ?? '' is unnecessary because toString() should never return null - even Null.toString() returns "null".

Upvotes: 3

Related Questions