我想在显示CircularProgressIndicator
之后重新开始未来。我该怎么做?
当我的电话没有数据/ wifi时,快照状态snapshot.connectionState == ConnectionState.done
为真,因此snapshot.data
为空。
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<List<ADBeanData>>(
future: makeGETRequest("http:www.mywebfite.com/load.php?hi=true"),
builder: (BuildContext context, AsyncSnapshot snapshot){
if(snapshot.connectionState == ConnectionState.done){
if(snapshot.data == null){
this.this_went_offline = true;
//timer_refresh_messages = new Timer.periodic(Duration(seconds: 3), (Timer t) => RestartWidget.restartApp(context));//I want to do something like this
//I want to restart the future after showing the CircularProgressIndicator
return Center(child: CircularProgressIndicator()); // loading
}
return PageView.builder(
itemCount: snapshot.data.length,
//do stuff
//The rest of my code contains the normal checks for connection state:
}else if(snapshot.connectionState == ConnectionState.waiting){
return Text("loading ...");
}else{
Future<List<ADBeanData>> makeGETRequest(String url) async {
ADBeanData ad_bean_data = new ADBeanData();
Response response = await get(url);
var json_data = json.decode(response.body);
List<ADBeanData> ad_bean_list = [];
for (var u in json_data) {
ADBeanData ad_bean = ADBeanData.set(
u["ad_id"],
u["user_id"],
u["category"]
);
ad_bean_list.add(ad_bean);
}
print(ad_bean_list.length);
return ad_bean_list;
}
答案 0 :(得分:0)
只需调用setState
即可“重启” Future
。
示例代码:
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<List<ADBeanData>>(
future: makeGETRequest("http:www.mywebfite.com/load.php?hi=true"),
builder: (BuildContext context, AsyncSnapshot snapshot){
if(snapshot.connectionState == ConnectionState.done){
if(snapshot.data == null){
this.this_went_offline = true;
if(!timer_refresh_messages?.isActive()) {
timer_refresh_messages = new Timer.periodic(Duration(seconds: 3), (Timer t) => setState((){}));
}
return Center(child: CircularProgressIndicator()); // loading
}
timer_refresh_messages?.cancel();
return PageView.builder(
itemCount: snapshot.data.length,
//do stuff
//The rest of my code contains the normal checks for connection state:
}else if(snapshot.connectionState == ConnectionState.waiting){
return Text("loading ...");
}else{
由于makeGETRequest()
在FutureBuilder
内,因此通过setState
重新加载此段也将重新加载数据。