我正在寻找一种从我的flutter应用程序检查互联网连接的方法。我试着遵循下面的流程。
-
使用查找
final result = await InternetAddress.lookup('example.com')
并检查result.isNotEmpty && result[0].rawAdress.isNotEmpty
-
使用internet_connection_checker插件
final result = await InternetConnectionChecker().hasConnection
我的测试设备(真实设备(连接到wifi,但需要登录才能使用它(但当时没有登录(。即使应用程序不能使用互联网,结果似乎总是返回true。
附加信息
当我试图通过设备浏览器中的地址(1.1.1.1、google.com、example.com等(使用互联网时,它总是重定向到登录页面。我认为这可能是一个问题,为什么互联网状态检查总是返回true。
有人知道我可能做错了什么吗?或者我该怎么做才能得到我想要的?
谢谢
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:connectivity/connectivity.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'dart:async';
// import 'dart:io';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
////////////////// CHECK CONNECTIVITY CONTINUOUSLY ///////////////////////
// Define Variables
StreamSubscription connectivitySubscription;
ConnectivityResult previousresult;
@override
void initState() {
super.initState();
connectivitySubscription = Connectivity()
.onConnectivityChanged
.listen((ConnectivityResult nowresult) {
if (nowresult == ConnectivityResult.none) {
// print('Not Connected');
//TODO Flutter Toaster for None
Fluttertoast.showToast(
msg: "Network Connection Error",
backgroundColor: Colors.black,
textColor: Colors.white,
fontSize: 16.0,
);
}
// when mobile and wifi network connected
else if (previousresult == ConnectivityResult.none) {
// print('Connected');
if (nowresult == ConnectivityResult.mobile) {
// print('Mobile Network Connected');
//TODO Flutter Toaster for Mobile
Fluttertoast.showToast(
msg: "Mobile Network Connected",
backgroundColor: Colors.black,
textColor: Colors.white,
fontSize: 16.0,
);
} else if (nowresult == ConnectivityResult.wifi) {
// print('WiFi Network Connected');
//TODO Flutter Toaster for WiFi
Fluttertoast.showToast(
msg: "WiFi Network Connected",
backgroundColor: Colors.black,
textColor: Colors.white,
fontSize: 16.0,
);
}
}
previousresult = nowresult;
});
}
@override
void dispose() {
super.dispose();
connectivitySubscription.cancel();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.cyan,
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Connectivity Status',
style: TextStyle(
fontSize: 25.0,
),
),
],
),
),
);
}
}