在我的 API 呼叫中,我將映射中的鍵和值存盤在串列中。我想在我的 ListView 中訪問這些鍵和值,并將它們顯示在我的小部件中的 Text 中。我怎樣才能做到這一點?
API 請求
Future<List<Presence>> getPresencesByAthleteId(
int depId, int teamId, int? id, context) async {
try {
final response = await http.get(
Uri.parse(
'$uri/get-presences-by-athlete-id?depId=$depId&teamId=$teamId&id=$id'),
headers: {
'Authorization': 'Basic ...',
'Content-Type': 'application/json',
'Accept': 'application/json'
});
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
if (response.statusCode == 200) {
if (response.body.isNotEmpty) {
print('response.body.isNotEmpty');
Map map = json.decode(response.body);
List<Presence>? presencesList = [];
map.forEach((key, value) {
presencesList.add(Presence(
date: map.entries.first.key, count: map.entries.first.value));
print('$key,$value');
});
return presencesList.toList();
} else if (response.body.isEmpty) {
print('response.body.isEmpty');
}
}
} catch (e) {
logger.e(e.toString());
}
return getPresencesByAthleteId(depId, teamId, id, context);
}
我的串列視圖
child: FutureBuilder<List<Presence>>(
future: getPresencesByAthleteId(_athlete[i].department!.id, widget._team.teamKey!.teamId, _athlete[i].id, context),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
return ListView.builder(
shrinkWrap: true,
primary: true,
physics: const ClampingScrollPhysics(),
scrollDirection: Axis.horizontal,
cacheExtent: 34,
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text('${(index 1).toString()}.'),
const SizedBox(
width: 5,
),
Text(snapshot.data[index].toString()),
const SizedBox(
width: 20,
),
Text(
'{presencesList[index]',
style: const TextStyle(color: Colors.blue),
)
],
)
],
),
);
});
} else if (snapshot.hasError) {
logger.e('${snapshot.error}');
}
return const Center(
heightFactor: 20,
child: CircularProgressIndicator.adaptive(),
);
})
我的存在模型
class Presence {
String date;
int count;
Presence({required this.date, required this.count});
factory Presence.fromJson(Map<String, dynamic> json) => Presence(
date: json['date'],
count: json['count'] as int,
);
Map<String, dynamic> toJson() => {
"date": date,
"count": count,
};
}
Postman 的 api 是我存盤在串列中的地圖
{
"10-11-2022":1,
"9-11-2022":4,
"7-11-2022":1
}
uj5u.com熱心網友回復:
代替
Text(snapshot.data[index].toString()),
你可以簡單地做
Text(snapshot.data[index].date),
或者
Text(snapshot.data[index].count.toString()),
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/531644.html
標籤:扑镖
