I have a snippet of code which I copied from 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 goes wrong here?
The problem here is that type inference fails in an unexpected way. The solution is to provide a type argument to the
map
method.The more complicated answer is that while the type of
children
isList<Widget>
, that information doesn't flow back towards themap
invocation. This might be becausemap
is followed bytoList
and because there is no way to type annotate the return of a closure.You can Cast dynamic List to List With specific Type:
I think that you use _buildBody in the children properties of some widget, so children expect a List Widget (array of Widget) and _buildBody returns a 'List dynamic'.
In a very simple way, you can use an variable to return it:
Example (flutter create test1 ; cd test1 ; edit lib/main.dart ; flutter run):
Another example using a Widget (oneWidget) within a List of Widgets(arrayOfWidgets). I show how extents a widget (MyButton) to personalize a widget and reduce the size of code:
I made a complete example that I use dynamic widgets to show and hide widgets on screen, you can see it running online on dart fiddle, too.
Maybe it helps someone. If it was is useful to you, let me know clicking in up arrow, please. Thanks.
https://dartpad.dev/b37b08cc25e0ccdba680090e9ef4b3c1
I have solve my problem by converting
Map
toWidget