Home > Software design >  Type Casting Problem While Using `List.map`
Type Casting Problem While Using `List.map`

Time:03-03

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.

CodePudding user response:

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(),
  • Related