[英]How to update the initial state on Flutter
我正在构建一个 flutter 页面,向用户显示存储在后端的信用卡列表,并允许用户删除现有的卡。
为了从后端获取卡片,我使用initState()
。 请注意controller.getCreditCards()
返回一个Future<List<CreditCardSummary>>
:
@override
void initState() {
super.initState();
_futureCreditCards = controller.getCreditCards();
}
然后使用FutureBuilder
呈现此列表,就像文档建议的那样:
Widget build(BuildContext context) {
return FutureBuilder<List<CreditCardSummary>>(
future: _futureCreditCards,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Scaffold(
// My page that renders all the cards goes here
// Inside this future builder I can access the cards list with snapshot.data
);
} else if (snapshot.hasError) {
return Text('ERROR');
}
// Show a loading screen while the data is beeing fetched:
return const CircularProgressIndicator();
});
}
这一切都很好,只有当我需要更新这些数据时问题才会出现。 例如,当用户删除信用卡时,我想从列表中删除该卡并使用新版本的列表重新呈现页面,但我不知道这样做的好方法。
为了获取更新的数据/刷新 FutureBuilder,您需要重新分配 future 变量。
对于你的情况,每当你想更新时,
_futureCreditCards = controller.getCreditCards();
setState((){});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.