Search code examples
flutterflutter-webflutter-widgetflutter-typeahead

Flutter add to List<Widget> crashes beacuase of type issues


I have an issue I don't understand.

   Widget build(BuildContext context) {
    List<Widget> menuList = menuCategories.map((category) {
      return ExpansionTile(
          title: CustomExpansionTileHeader(
            icon: category.icon,
            label: category.label,
          ),
          children: category.children
              .map((item) => ListTile(
                    title: Text(item.label),
                    onTap: item.onTap,
                  ))
              .toList());
    }).toList();
    print(menuList);
    menuList.insert(
        0,
        DrawerHeader(
            child: Text(
              '',
              style: TextStyle(color: Colors.white, fontSize: 25),
            ),
            decoration: BoxDecoration(
              color: Colors.green,
              // image: DecorationImage(
              // fit: BoxFit.fill,
              // image: AssetImage('assets/images/cover.jpg'))),
            )));
    return Drawer(
      child: ListView(padding: EdgeInsets.zero, children: menuList

As you can see I'm trying to create List type Widget withsome ExpansionTile widgets but also add DrawerHeader as index 0. Afterwards, I want to return the list as in Drawer widget in children List.

When I print menuList (before adding DrawerHeader to the list) it prints [ExpansionTile, ExpansionTile, ExpansionTile, ExpansionTile], when I print menuList.runtimeType I get List type ExpansionTile. And this is the part I don't understand. The list was supposed to be List of Widget and it was somehow changed.

This causes crash when I add DrawerHeader to the List as it's different tipe.

If it's important, I'm building Flutter web app.

Please help :)


Solution

  • When you do List<Widget> menuList = menuCategories.map((category) {, specify the type with the generic field. Dart is incorrectly inferring that you want this iterable to be of type ExpansionTile.

    Do

    List<Widget> menuList = menuCategories.map<Widget>((category) {
    

    to more explicitly tell dart what type you want this to be.