[英]Flutter : how to check connectivity using firestore
How to check connectivity and show images only when there is an internet connection else show circular progress indicator.如何仅在有互联网连接时检查连接并显示图像,否则显示循环进度指示器。 In my following code indicator is just appearing only for a second even when there is not an internet connection.
在我的以下代码中,即使没有互联网连接,指示器也只会出现一秒钟。
class About extends StatelessWidget {
List<Image> _listOfImages = <Image>[];
@override
Widget build(BuildContext context) {
SizeConfig().init(context);
return Scaffold(
body: ListView(
scrollDirection: Axis.vertical,
children: <Widget>[
Padding(
padding: EdgeInsets.only(
left: SizeConfig.safeBlockHorizontal * 5,
top: SizeConfig.safeBlockHorizontal * 5,
right: SizeConfig.safeBlockHorizontal * 5),
child: Material(
borderRadius: BorderRadius.circular(24.0),
child: SizedBox(
width: SizeConfig.safeBlockHorizontal * 80,
height: SizeConfig.safeBlockHorizontal * 80,
child: StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection('About').snapshots(),
builder: (context, snapshot) {
if (snapshot.data.documents.length == 0){
return Center(
child:
CircularProgressIndicator()
);
}
else {
return ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (BuildContext context, int index) {
_listOfImages = [];
Check this package out:检查此 package :
It is a great package/library which does this job for you.这是一个很棒的包/库,可以为您完成这项工作。 To make use of that, just import and do like this the below example:
要利用它,只需导入并执行以下示例:
Future<bool> check() async {
var connResult = await (Connectivity().checkConnectivity());
if (connResult == ConnectivityResult.mobile) {
return true;
} else if (connResult == ConnectivityResult.wifi) {
return true;
}
return false;
}
Note that on Android, this does not guarantee connection to Internet.
请注意,在 Android 上,这并不能保证连接到 Internet。 For instance, the app might have wifi access but it might be a VPN or a hotel WiFi with no access.
例如,该应用程序可能具有 wifi 访问权限,但它可能是 VPN 或无法访问的酒店 WiFi。
Alternate Usage替代用法
The main idea is to check whether the link can be opened or not, we're using google.com
in this case.主要思想是检查链接是否可以打开,在这种情况下我们使用
google.com
。 You can then, return your boolean
to do your stuffs based upon that.然后,您可以退回您的
boolean
以在此基础上完成您的工作。
import 'dart:io'
bool isConnected = false;
// use try-catch to do this operation, so that to get the control over this
// operation better
try{
final result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
// do the operation for connected, or change the bool to True for connected
setState(() => isConnected = true);
}
} on SocketException catch (_) {
setState(() => isConnected = false);
}
To know more the InternetAddress
, follow this: InternetAddress Class .要了解
InternetAddress
的更多信息,请按照以下说明操作: InternetAddress Class 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.