Home > Mobile >  How to pass context to a function in a class which I am mapping over in Flutter?
How to pass context to a function in a class which I am mapping over in Flutter?

Time:01-04

I have several widgets in my app which build "cards" (ListTiles) by mapping data as follows:

return FutureBuilder<List<MyCard>>(
                future: MyCard.readData(snapshot.data),
                builder: (context, cards) {
                  if (cards.hasData) {
                    final card = cards.data!;
                    return Expanded(
                        child: ListView(
                            padding: const EdgeInsets.all(16),
                            children: card.map(MyCard.buildCard).toList()));
                  } else {
                    return const Text("No data");
                  }
                });

The method buildCard (for MyCard class) is as follows:

static Widget buildCard(MyCard card) {
    var dateFormat = DateFormat('MM/dd/yyyy');
    return Column(
      children: [
        Align(
            alignment: Alignment.centerRight,
            child: Text(dateFormat.format(card.createdOn.toDate()))),
        const SizedBox(height: 6),
        ListTile(
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(30)),
          tileColor: Colors.white,
          leading: CircleAvatar(child: Text(card.subCategory)),
          title: Text("Score: "   card.score   " Misses: "   card.misses),
          subtitle: card.comment.isNotEmpty
              ? Text("Comment(s): "   card.comment)
              : null,
          trailing: IconButton(
              icon: const Icon(Icons.arrow_forward_ios),
              onPressed: checkCard(card)), //need to pass context to checkCard
        ),
        const SizedBox(height: 18),
      ],
    );
  }

But I need to get the context to the buildCard method (because I need to pass it to the checkCard method since I am trying to call showDialog() in said method and I can't figure out how to pass the context.

I tried to simply add the BuildContext field to the buildCard method as follows:

static Widget buildCard(MyCard card, BuildContext context) {
    var dateFormat = DateFormat('MM/dd/yyyy');
    return Column(
      children: [
        Align(
            alignment: Alignment.centerRight,
            child: Text(dateFormat.format(card.createdOn.toDate()))),
        const SizedBox(height: 6),
        ListTile(
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(30)),
          tileColor: Colors.white,
          leading: CircleAvatar(child: Text(card.subCategory)),
          title: Text("Score: "   card.score   " Misses: "   card.misses),
          subtitle: card.comment.isNotEmpty
              ? Text("Comment(s): "   card.comment)
              : null,
          trailing: IconButton(
              icon: const Icon(Icons.arrow_forward_ios),
              onPressed: checkCard(card, context)),
        ),
        const SizedBox(height: 18),
      ],
    );
  }

but when I try to pass it to the method in my Widgets it doesn't seem to work. I figured I would pass it as follows:

return FutureBuilder<List<MyCard>>(
                future: MyCard.readData(snapshot.data),
                builder: (context, cards) {
                  if (cards.hasData) {
                    final card = cards.data!;
                    return Expanded(
                        child: ListView(
                            padding: const EdgeInsets.all(16),
                            children: card.map(MyCard.buildCard(context)).toList()));
                  }

But get the following:

Error message

CodePudding user response:

Try the following code:

ListView.builder(
  itemCount: card.length,
  itemBuilder: (context, index) {
    return MyCard.buildCard(card[index], context);
  },
),

CodePudding user response:

Change your code from

 ListView(
    padding: const EdgeInsets.all(16),
    children: card.map(MyCard.buildCard(context)).toList()));
    

to

ListView.builder(
  itemCount: card.length,
  itemBuilder: (context, index) {
    return MyCard.buildCard(card[index], context);            
  • Related