How to add initial widgets before ListView's item builder, or How to inject Widgets on top of a ListView.itemBuilder?

Issue

In this example I want to create a ListView of ListViewTiles populated by the argument List of ItemData.
I want to place a header Image as the top widget of the same ListView.
The Image must scroll with the rest of the ListTiles.

  Widget _buildListViewWithHeader(BuildContext context, Image banner, List<ItemData> items) {
    return ListView.builder(
      itemBuilder: (context, index) {
        return ListTile(
          leading: items[index].leading,
          title: items[index].title,
          trailing: items[index].trailing,
        );
      },
    );
  }

How do I place the Image at the top of this ListView?

Is there a generic way to pass a list of widgets to a listView and place them before the item builder’s generated ones?

Solution

Here is a more generic way to inject any number of widgets:

Widget _buildListViewWithHeader(BuildContext context, List<Widget> topWidgets, List<ItemData> itemData) {
  return ListView.builder(
    itemCount: topWidgets.length + itemData.length,
    itemBuilder: (context, index) {

      if (index < topWidgets.length) {//<-- returns each injected widget in list.
        return topWidgets[index];
      }

      int itemIndex = index - topWidgets.length; //<-- subtract the number of widgets injected.
      return ListTile(
        leading: itemData[itemIndex].leading,
        title: itemData[itemIndex].title,
        trailing: itemData[itemIndex].trailing,
      );
    },
  );

Answered By – Joel Broström

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.