flutter - 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;
}
解决方案
您可以使用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();
}
}
},
)
推荐阅读
- java - Firebase 实时数据库在使用应用时仍然无效。这怎么可能?很奇怪
- reactjs - 在反应功能组件的函数内调用 props.myFunction()
- c - 需要有关在 C 中以不同方式编写 For 循环的建议,命令行参数
- reactjs - 第一次设置状态然后使用状态时如何从 inifite 循环中停止 useEffect
- python - Python Matplotlib 按类别和聚合排列子图
- css - 如何用 flexbox div 填充背景图像
- java - 如何通过 CMD 启动 JavaFX 程序?
- angular - 我可以根据屏幕尺寸在不同的模板中使用相同的 Angular 路由器插座吗
- javascript - 选择数组内的随机点,将它之前的项目移动到最后
- ruby - 在 debian 中安装 rbenv 时找不到 gem 命令