当snapshot.data为null时,如何再次调用FutureBuilder?

时间:2020-05-26 21:20:41

标签: flutter dart

我想在显示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;
  }

1 个答案:

答案 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重新加载此段也将重新加载数据。