reisako
reisako

Reputation: 43

Flutter - How to list out forEach() value in ListView builder?

Hi I am trying to list data from JSON to Listview Builder . But Flutter is giving me this error: Column's children must not contain any null values, but a null value was found at index 0

I tried to map each one like this inside the listview

alo[Index]['rewards'].forEach((k, v) {
                      Text(v['name']);
                    }),

Here is my full code:

            shrinkWrap: true,
            itemCount: alo.length,
            itemBuilder: (BuildContext ctxt, int Index) {
              return Card(
                  child: Padding(
                padding: const EdgeInsets.all(15.0),
                child: Column(
                  children: <Widget>[
                    alo[Index]['rewards'].forEach((k, v) {
                      Text(v['name']);
                    }),


                  ],
                ),
              ));
            });

Is there any solution to this? Thank you!

Upvotes: 3

Views: 9391

Answers (2)

Pablo Barrera
Pablo Barrera

Reputation: 10963

The thing is forEach() doesn't return anything, you could use map() instead, like this:

children: alo[Index]['rewards'].values.map<Widget>((v) => Text(v['name'])).toList()

If you want to add more widgets, you could do something like this:

Column(
  children: <Widget>[
    Column(
      children: alo[Index]['rewards']
          .values
          .map<Widget>((v) => Text(v['name']))
          .toList(),
    ),
    Text('Other widget'),
  ],
)

Upvotes: 7

RegularGuy
RegularGuy

Reputation: 3676

You have two options, if you don't have any rewards then you can

a) Leave an empty card

        shrinkWrap: true,
        itemCount: alo.length,
        itemBuilder: (BuildContext ctxt, int Index) {
          return Card(
              child: Padding(
            padding: const EdgeInsets.all(15.0),
            child: Column(
              children: <Widget>[
              alo[Index]['rewards']!=null?
                alo[Index]['rewards'].forEach((k, v) {
                  return Text(v['name']);
                }):SizedBox()


              ],
            ),
          ));
        });

or

b) don't render any card

        shrinkWrap: true,
        itemCount: alo.length,
        itemBuilder: (BuildContext ctxt, int Index) {
          return alo[Index]['rewards']!=null?Card(
              child: Padding(
            padding: const EdgeInsets.all(15.0),
            child: Column(
              children: <Widget>[
                alo[Index]['rewards'].forEach((k, v) {
                  return Text(v['name']);
                }),


              ],
            ),
          )):SizedBox();
        });

Upvotes: 1

Related Questions