我的应用程序中有几个小部件,它们通过Map数据构建“卡片”(ListTiles),如下所示:
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");
}
});
方法buildCard(用于MyCard类)如下所示:
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),
],
);
}
但是我需要将上下文传递给buildCard方法(因为我需要将它传递给checkCard方法,因为我试图在该方法中调用showDialog(),但我不知道如何传递上下文)。
我尝试简单地将BuildContext字段添加到buildCard方法中,如下所示:
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),
],
);
}
但是当我试图将它传递给我的Widget中的方法时,它似乎不起作用。我想我应该按如下方式传递它:
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()));
}
但得到以下:
2条答案
按热度按时间rqdpfwrv1#
请尝试以下代码:
9o685dep2#
更改您的代码
到