Home > Net >  Dart only can infer type from `map` sometimes
Dart only can infer type from `map` sometimes

Time:12-26

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.

CodePudding user response:

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:

List<DataColumn> columns = data![0]
    .keys
    .map((keyName) => DataColumn(
          label: Expanded(
            child: Text(
              keyName,
              style: const TextStyle(fontStyle: FontStyle.italic),
            ),
          ),
        ))
    .toList();

Two: define the type in map:

var columns = data![0]
    .keys
    .map<DataColumn>((keyName) => DataColumn(
          label: Expanded(
            child: Text(
              keyName,
              style: const TextStyle(fontStyle: FontStyle.italic),
            ),
          ),
        ))
    .toList();

Because the map doesn't know which kind of data it deals with so it considers it as dynamic and it will through you an exception when try to pass list of dynamic to list of DataColumn.

CodePudding user response:

Probably, the type of data![0].keys is different from data!.

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:

var data = ['a', 'b', 'c'];

var mappedData = data.map((x) => x.length);

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.

  • Related