0

I am trying to use the List.map function but I can't make it work. Here I have a data variable of type List<List<dynamic>> and when I am trying to perform the below operation on the data, it throws exceptions.

rows: data.map((i) {
    DataRow(
      cells: <DataCell>[
        DataCell(Text(i[0].text)),
        DataCell(Text(i[1].text)),
        DataCell(Text(i[3].text)),
      ],
    );
  }
).toList(),

The above code throws the following exception: type List<dynamic> is not a subtype of type List<DataRow>

I tried different solutions provided on the above StackOverflow link. i.e

rows: data.map<DataRow>((i) {
    DataRow(
      cells: <DataCell>[
        DataCell(Text(i[0].text)),
        DataCell(Text(i[1].text)),
        DataCell(Text(i[3].text)),
      ],
    );
  }
).toList(),

or:

rows: data.map((i) {
    DataRow(
      cells: <DataCell>[
        DataCell(Text(i[0].text)),
        DataCell(Text(i[1].text)),
        DataCell(Text(i[3].text)),
      ],
    );
  }
).toList() as List<DataRow>,

or:

rows: List<DataRow>.from(data.map((i) {
    DataRow(
      cells: <DataCell>[
        DataCell(Text(i[0].text)),
        DataCell(Text(i[1].text)),
        DataCell(Text(i[3].text)),
      ],
    );
  })
).toList(),

None seems to work, while applying the above methods, in some cases I get a different exception from the one I mentioned at the start i.e in some cases I get this exception: type 'Null' is not a subtype of type 'DataRow' in type cast

It works if I am not using a List.map. i.e if I declare a List<DataRow> variable and then populate it with a for loop. Then it works.

   rows: buildItems(data),
    );
  }

  List<DataRow> buildItems(data) {
    List<DataRow> rows = [];
    for (var i in data) {
      rows.add(DataRow(cells: [
        DataCell(Text(i[0].text)),
        DataCell(Text(i[1].text)),
        DataCell(Text(i[3].text)),
      ]));
    }
    return rows;
  }

The above code works, it's just that I can't make it work while using List.map.

2
  • 2
    Have you forgor return statement inside of map function? Commented Mar 2, 2022 at 9:57
  • LOL! I think so. Probably I didn't return anything. Commented Mar 2, 2022 at 10:00

1 Answer 1

1

You need to add a return statement to your map like so

rows: data.map((i) {
    return DataRow(
      cells: <DataCell>[
        DataCell(Text(i[0].text)),
        DataCell(Text(i[1].text)),
        DataCell(Text(i[3].text)),
      ],
    );
  }
).toList(),
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.