Type 'List <dynamic>' is not a subtype of type 'List <Widget>'

I have a piece of code that I copied from the Firestore example:

Widget _buildBody(BuildContext context) {
    return new StreamBuilder(
      stream: _getEventStream(),
      builder: (context, snapshot) {
        if (!snapshot.hasData) return new Text('Loading...');
        return new ListView(
          children: snapshot.data.documents.map((document) {
            return new ListTile(
              title: new Text(document['name']),
              subtitle: new Text("Class"),
            );
          }).toList(),
        );
      },
    );
  }

But I get this error

type 'List<dynamic>' is not a subtype of type 'List<Widget>'

What is wrong here?

+34
source share
3 answers

The problem is that type inference terminates unexpectedly. The solution is to provide a type argument to the method map.

snapshot.data.documents.map<Widget>((document) {
  return new ListTile(
    title: new Text(document['name']),
    subtitle: new Text("Class"),
  );
}).toList()

A more complex answer is that if the type childrenis equal List<Widget>, this information does not return to the call map. This may be due to what mapfollows toListand because there is no way to introduce a short circuit return annotation.

+57
source

, Map Widget

      children: snapshot.map<Widget>((data) => 
               _buildListItem(context, data)).toList(),
+1

You can cast a dynamic list to a list with a specific type:

List<'YourModel'>.from(_list.where((i) => i.flag == true));
0
source

Source: https://habr.com/ru/post/1695625/


All Articles