Как мне снова вызвать FutureBuilder, когда snapshot.data имеет значение null? - PullRequest
0 голосов
/ 27 мая 2020

Я хочу перезапустить будущее после отображения CircularProgressIndicator. Как мне выполнить sh это?

Когда на моем телефоне нет данных / Wi-Fi, состояние снимка snapshot.connectionState == ConnectionState.done истинно , поэтому snapshot.data имеет значение null.

 @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 голосов
/ 27 мая 2020

Просто позвоните 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 также перезагрузит данные.

...