The following code in my test Flutter app fails with Expected a value of type 'List<DataColumn>', but got one of type 'List<dynamic>'
var columns = data![0]
.keys
.map((keyName) => DataColumn(
label: Expanded(
child: Text(
keyName,
style: const TextStyle(fontStyle: FontStyle.italic),
),
),
))
.toList();
var rows = data!
.map((value) => DataRow(
cells: <DataCell>[
DataCell(Text("${value['name']}")),
DataCell(Text("${value['age']}")),
DataCell(Text("${value['role']}")),
],
))
.toList();
If I explicitly pass the type to the first map
with
.map<DataColumn>((keyName) => DataColumn(
it works fine.
So why does the first map needed the type passed, but the second does not. This feels similar to this SO question. But the answer there get’s the code to work, but does not explain why it only happens in some cases.
2
Answers
You need to define the
type
either in variable or in map type. You have two option to do that.One: define the type when you define variable like this:
Two: define the type in map:
Because the
map
doesn’t know which kind of data it deals with so it considers it asdynamic
and it will through you an exception when try to pass list ofdynamic
to list ofDataColumn
.Probably, the type of
data![0].keys
is different fromdata!
.Sometimes the type cannot be inferred, for example if you have a list of strings that use a map with a function that returns an integer:
In this case, the type of the elements returned by the map function is inferred as dynamic.
It is a good practice to specify the type returned by map explicitly, to avoid potential type errors.