首页 > 解决方案 > Flutter:检查互联网连接并根据输出导航?

问题描述

我是新来的,我想检查互联网是否可用,根据情况,屏幕必须改变。我已经编写了下面的代码(屏幕开关工作正常),但我无法获得布尔输出(互联网)。当我在检查互联网类中删除 Future 时,它​​会引发错误。你能解决这个问题吗:

class _ScreenState extends State<ChannelScreen> {
bool isInternet;
bool result;

  @override
  void initState() {
    // TODO: implement initState
    result = check();
    super.initState();
  }

  @override

  Widget _buildChild() {


        print ("The output “);
        print (result);
       if (result != Null && result == true) {
// if internet is ON
return Container();
                }
//if internet is off
       return Container();
  }


  Widget build(BuildContext context) {
    return new Container(child: _buildChild());
  }
}


Future<bool> check()   async{
  var connectivityResult =   await Connectivity().checkConnectivity();
  if (connectivityResult == ConnectivityResult.mobile) {
    print ("******* Mobile is ON ******");
    return true;
  } else if (connectivityResult == ConnectivityResult.wifi) {
    print ("******* Wifi is ON ******");
    return true;
  }
  print ("No connectivity");
  return false;
}

标签: flutter

解决方案


您可以使用StreamBuilder

StreamBuilder(
  stream: Connectivity().onConnectivityChanged,
  builder: (context, snapshot) {
    // Use this to avoid null exception
    if (snapshot.connectionState == ConnectionState.none) {
      return CircularProgressIndicator();
    } else {
      ConnectivityResult result = snapshot.data;

      // Check Connectivity result here and display your widgets
      if(ConnectivityResult.none) {
        yourWidgetForNoInternet();
      } else {
        yourWidgetForInternet();
      }
    }
  },
)

推荐阅读