Cannot map a list to a widget

2,110

Solution 1

The issues is using the ListView.builder, the builder function expects you to return one Widget at a time corresponding to the index provided. Use ListView directly instead.

Example:

ListView(
  children: items.map((item) => ItemWidget(item: item)).toList(),
);

Hope that helps!

Solution 2

If you want to use ListView.builder then you can use as following. This may helps you.

body: ListView.builder(
      itemCount: items == null ? 0 : items.length,
      itemBuilder: (BuildContext context, int index) {
        return ItemWidget(
          item: items[index],
        );
      },
    ),
Share:
2,110
newbie99
Author by

newbie99

Updated on December 12, 2022

Comments

  • newbie99
    newbie99 over 1 year

    I have a hardcoded list that I want to map it to a list of widgets. The code below shows squiggly lines with the error The return type 'List<ItemWidget>' isn't a 'Widget', as defined by anonymous closure.dart(return_of_invalid_type_from_closure).

    .................MISSING CODE....................
    
    ListView.builder(
      itemBuilder: (context, index) => items.map((item) => ItemWidget(item: item)).toList();
    ) 
    
    ..................MISSING CODE....................
    
    class ItemWidget extends StatelessWidget{
    
      final Item item;
    
      ItemWidget({this.item});
    
      @override
      Widget build(BuildContext context) {
        return Column(
          children: <Widget>[
            Expanded(
              child: FittedBox(
                fit: BoxFit.fill,
                child: Image.asset(item.iconPath)
              )
            ),
            Padding(
              padding: const EdgeInsets.only(top: 15.0),
              child: Text(item.name),
            )
          ],
        );
      }
    
    }
    
    

    EDIT:

    This is the list of items, currently I hold just an item for testing purposes.

    List<Item> items = [
      Item(name: 'Medicines', iconPath: '$ICON_BASE_PATH/medicines.svg'),
    ];
    

    If you have any idea please let me know, thanks!