194

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?

11 Answers 11

401

The problem here is that type inference fails in an unexpected way. The solution is to provide a type argument to the map method.

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

The more complicated answer is that while the type of children is List<Widget>, that information doesn't flow back towards the map invocation. This might be because map is followed by toList and because there is no way to type annotate the return of a closure.

9
  • 2
    May be related to strong-mode or flutter using Dart 2. Apr 2, 2018 at 0:55
  • 1
    TBH I haven't managed to reproduce his bug. Since his code is inferred as a List<ListTile> even without specifying it to map. Apr 2, 2018 at 1:31
  • 3
    Well that solved the issue. But it is a bit strange, I am new to dart, so I cannot really tell I understood it.
    – Arash
    Apr 2, 2018 at 3:31
  • 1
    I was facing the same issue (But my scenario was different). I think this is happening because of Dart 2 strong type. Once I changed the variable declaration to List<Widget> it started working. May 5, 2018 at 6:31
  • 2
    Could you explain why the new in new ListTile is necessary?
    – Binajmen
    May 25, 2021 at 22:57
47

I had a list of strings in firestore that I was trying to read in my app. I got the same error when I tried to cast it to List of String.

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

This solution helped me. Check it out.

var array = document['array']; // array is now List<dynamic>
List<String> strings = List<String>.from(array);
0
36

You can Cast dynamic List to List With specific Type:

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

I have solve my problem by converting Map to Widget

children: snapshot.map<Widget>((data) => 
    _buildListItem(context, data)).toList(),
2
  • Thank you for such a simple answer! Aug 27, 2020 at 21:02
  • 2
    why It's not working for me? dart null-safety Sep 17, 2021 at 2:55
7

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:

// you can build your List of Widget's like you need
List<Widget> widgets = [
  Text('Line 1'),
  Text('Line 2'),
  Text('Line 3'),
];

// you can use it like this
Column(
  children: widgets
)

Example (flutter create test1 ; cd test1 ; edit lib/main.dart ; flutter run):

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List<Widget> widgets = [
    Text('Line 1'),
    Text('Line 2'),
    Text('Line 3'),
  ];

  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("List of Widgets Example")),
        body: Column(
          children: widgets
        )
      )
    );
  }

}

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:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List<Widget> arrayOfWidgets = [
    Text('My Buttons'),
    MyButton('Button 1'),
    MyButton('Button 2'),
    MyButton('Button 3'),
  ];

  Widget oneWidget(List<Widget> _lw) { return Column(children: _lw); }

  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("Widget with a List of Widget's Example")),
        body: oneWidget(arrayOfWidgets)
      )
    );
  }

}

class MyButton extends StatelessWidget {
  final String text;

  MyButton(this.text);

  @override
  Widget build(BuildContext context) {
    return FlatButton(
      color: Colors.red,
      child: Text(text),
      onPressed: (){print("Pressed button '$text'.");},
    );
  }
}

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.

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List item = [
    {"title": "Button One", "color": 50},
    {"title": "Button Two", "color": 100},
    {"title": "Button Three", "color": 200},
    {"title": "No show", "color": 0, "hide": '1'},
  ];

  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("Dynamic Widget - List<Widget>"),backgroundColor: Colors.blue),
        body: Column(
          children: <Widget>[
            Center(child: buttonBar()),
            Text('Click the buttons to hide it'),
          ]
        )
      )
    );
  }

  Widget buttonBar() {
    return Column(
      children: item.where((e) => e['hide'] != '1').map<Widget>((document) {
        return new FlatButton(
          child: new Text(document['title']),
          color: Color.fromARGB(document['color'], 0, 100, 0),
          onPressed: () {
            setState(() {
              print("click on ${document['title']} lets hide it");
              final tile = item.firstWhere((e) => e['title'] == document['title']);
              tile['hide'] = '1';
            });
          },
        );
      }
    ).toList());
  }
}

Maybe it helps someone. If it was is useful to you, let me know clicking in up arrow, please. Thanks.

https://dartpad.dev/b37b08cc25e0ccdba680090e9ef4b3c1

3
  • 1
    This no longer seems to work. Can't assign e.g. Text('My Buttons') into the List<Widget> array. Getting The element type 'Text' can't be assigned to the list type 'Widget'. What would be a workaround for this?
    – shaimo
    Jul 15, 2020 at 13:58
  • Text is a Widget and can be an element of List<Widget>. Check this pad https://dartpad.dev/6a908fe99f604474fd052731d59d059c and tell me if it works to you.
    – lynx_74
    Jul 23, 2020 at 0:00
  • "The element type 'List<Widget>' can't be assigned to the list type 'Widget'." from your very first example. Doesn't seem to work anymore
    – Petro
    Dec 22, 2020 at 0:43
7

My Solution is, you can cast List<dynamic> into List<Widget>, you can add a simple code after snapshot.data.documents.map into snapshot.data.documents.map<Widget>, like the code i will show you below

From this

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

Into this

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

This works for meList<'YourModel'>.from(_list.where((i) => i.flag == true));

3

Example:

List<dynamic> listOne = ['111','222']
List<String> ListTwo = listOne.cast<String>();
2

I think , after changing the type of List from dynamic to String & doing hot reload will give this error , hot restart is the solution..

Remember : hot restart only rebuild the build() function , not the whole class & declaring the List at the top of class is outside of build() function

1

changing to the list by adding .toList() resolved the issue

0
0

Changing

List list = [];

to this:

List<Widget> list = [];

Solved My Problem!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.