Flutter Future in Future 并设置 state()

时间:2021-03-15 17:33:19

标签: flutter dialog connection future

在有状态类 initState() 方法中,我正在调用一个函数来检查互联网连接(不是侦听器)。 然后在同一个类的 FutureBuilder 中,我给出了一个调用服务器的未来。现在的问题是,当我从其他页面导航回同一页面时,互联网连接关闭,然后我遇到以下问题

CheckConncection 函数:

 Future<bool> internetChecker(BuildContext context) async{
    if( await DataConnectionChecker().hasConnection){
      return true;
    }
    else{
      InternetStatus = "You are disconnected to the Internet. ";
      contentmessage = "Please check your internet connection";
      showDialogBox(InternetStatus,contentmessage,context);
      return false;
    }
  }

showDialog:

Widget showDialogBox(String err,String content ,BuildContext context) {
    showDialog(
      barrierDismissible: false,
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
              title: new Text(err),
              content: new Text(content),
              actions: <Widget>[
                new FlatButton(
                    onPressed: () async {
                      Navigator.of(context).pop();
                      if(await internetChecker(context)==true){
                        setState(() {

                        });
                      }
                      else{
                        showDialogBox('err', 'retry', context);
                      }
                    },
                    child: new Text("Try Again"))
              ]
          );
        }
    );
  }

请注意,我在 internetreconnection 上调用 setState()。但这仅在 initstate() 期间才有效。

现在,我尝试在我的 Future API 请求中检查相同的内容

Future<List<Map<String, dynamic>>> getMultipleData(String token) async {
  if(await DataConnectionChecker().hasConnection){
    try {
      ...
    } on SocketException catch (e) {
      print(e);
    }
   }
   else{
    showDialogBox('err','no internet',context);
   }
}

以前我遇到了以下异常,但现在不是,w=而且我还没有更改代码。那还能再来吗

[ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: Looking up a deactivated widget's ancestor is unsafe.

0 个答案:

没有答案
相关问题