页面中使用setState(() { });改变数据时,不希望再次调用接口。可以在构建函数之外的某个地方调用Future
。例如,在initState
中,将其保存在成员变量中,并将此变量传递给FutureBuilder
。
void initState() {
super.initState();
_mFuture = queryDetail();
}
queryDetail(){
...
}
FutureBuilder(
future: _mFuture,
builder: (BuildContext context, AsyncSnapshot snapshot) {
// 请求已结束
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
// 请求失败,显示错误
return Text("Error: ${snapshot.error}");
} else {
// 请求成功,显示数据
dto = snapshot.data;
return Scaffold(
appBar: Utils.AppBarContent("详情", context),
body: Container(
color: Color(0xffF6F6F6),
alignment: Alignment.topCenter,
padding: EdgeInsets.all(10),
child: _cardList(context,dto),
),
);
}
} else {
// 请求未结束,显示loading
return CircularProgressIndicator();
}
},
)