Raph117
Raph117

Reputation: 3821

Flutter toList() is making a list of <dynamic> type

I'm trying to render a list of widgets. To do this, I'm creating a list of RowDataEntry objects that looks like this:

class RowDataEntry {
  final Map<String, dynamic> values;

  RowDataEntry(this.values);
}

I then want to instantiate the list of entries like this like this:

final List<RowDataEntry> data = args['data'].subFunds.map((subFund) {
      final name = subFund.parameters["subFundName"];
      return RowDataEntry({"fundName": name, "status": Status('pass')});
    }).toList();

However, the "toList()" converts the list into a list of type dynamic, rather than of type RowDataEntry, and so I'm getting a compilation error.

I've tried casting but I can't get it to work. It would be great if someone could show me where I'm going wrong.

Thanks.

EDIT======================

I think the issue is with the args object. It looks like this:

final Map<String, dynamic> args = ModalRoute.of(context).settings.arguments;

Upvotes: 3

Views: 4513

Answers (1)

Nitrodon
Nitrodon

Reputation: 3435

Since args['data'] is of declared type dynamic, there is no type information about args['data'].subFunds available at compile time. Consequently, there is no way for the compiler to infer that map even has a type argument, let alone that the type argument should be RowDataEntry.

To obtain a List<RowDataEntry>, you will need to add type information at some point. The best point would probably be the class of args['data'] itself:

(args['data'] as SomeClass).subFunds.map( /* ... */ ).toList();

Presumably, this class declares subFunds as a property of type List<SubFund>, so Dart can infer both the type of the lambda parameter and the type argument of map.

Other options to fix type inference include:

  • declaring args['data'].subFunds as a List or List<SubFund>
  • explicitly giving map a type parameter

Upvotes: 1

Related Questions