skip to Main Content

How to pass data inside buildListItem function as a parameter?

When I add a third parameter data to buildListItem, it gives an error in the IDE:

The argument type ‘Widget’ can’t be assigned to the parameter type
‘Widget? Function(BuildContext, int)’.

final List<RapportData> data = snapshot.data!;

return ListView.separated(
  physics: const ScrollPhysics(),
  itemCount: data.length,
  itemBuilder: buildListItem, // how to pass `data`?
  separatorBuilder: (context, index) => const Divider(),
);

Widget buildListItem(BuildContext context, int index) {
  return GestureDetector(
    onTap: () {
      var rapportData = data[index]; //data is not avalable here
      onTapFunction(context, Group(rapportData));
    },
    child: ListTile(...
    
    ... 
}

2

Answers


  1. Certainly! You can achieve that by using an anonymous function directly inside the itemBuilder parameter. Here’s how you can do it:

    final List<RapportData> data = snapshot.data!;
    
    return ListView.separated(
      physics: const ScrollPhysics(),
      itemCount: data.length,
      itemBuilder: (context, index) {
        var rapportData = data[index];
        return GestureDetector(
          onTap: () {
            onTapFunction(context, Group(rapportData));
          },
          child: ListTile(
            // ListTile properties...
          ),
        );
      },
      separatorBuilder: (context, index) => const Divider(),
    );
    

    This way, you create an anonymous function directly inside the itemBuilder parameter, allowing you to access the data list within it.

    Login or Signup to reply.
  2. You can try pass parameter like this:

    final List<RapportData> data = snapshot.data!;
    
    return ListView.separated(
      physics: const ScrollPhysics(),
      itemCount: data.length,
      itemBuilder: (context, index) => buildListItem(context, data[index]),
      separatorBuilder: (context, index) => const Divider(),
    );
    
    Widget buildListItem(BuildContext context, RapportData rapportData) {
      return GestureDetector(
        onTap: () {
          //rapportData can use here
          onTapFunction(context, Group(rapportData));
        },
        child: ListTile(...
        
        ... 
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search