简体   繁体   中英

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

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:

错误信息

Try the following code:

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

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); 👈 Pass your context here which is received from the itemBuilder
  },
),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM