【发布时间】:2025-12-26 01:50:16
【问题描述】:
我有一个依赖互联网工作的安卓应用程序。我需要找到一种方法来一直检查互联网是否存在以查看应用程序。否则,当没有互联网时,我应该查看一个显示没有互联网连接的小部件。
我已经尝试过 connectivity 包,但它没有按预期工作,因为它只检查开关(wifi - 移动数据)是否打开或关闭,而不是真正的互联网。
我认为向网站发送获取请求并分析响应状态代码对我来说是个好主意。所以这是我尝试过的:
检查连接类
class CheckConnectionService {
Future<bool> checkConnection() async {
int theCode = 0;
Client client = Client();
try {
await client.get('http://www.google.com').then((value) {
theCode = value.statusCode;
});
}catch(e){
print(e);
return false;
}finally{
client.close();
}
if (theCode == 200){
return true;
}
return false;
}
}
然后在我的 main.dart 中,我尝试使用此检查一直运行,这是我的代码:
class MyApp extends StatefulWidget {
// This widget is the root of your application.
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool internetExists = true;
Stream checkIfOnline() async* {
await CheckConnectionService().checkConnection().then((check) {
print(check);
if (check){
internetExists = true;
setState(() {});
} else {
internetExists = false;
setState(() {});
}
});
}
@override
Widget build(BuildContext context) {
checkIfOnline();
if (!internetExists){
return MaterialApp(
title: 'G-Attend',
home: NoInternet(),
);
} else{
return MaterialApp(
theme: ThemeData(
fontFamily: 'Anton',
primaryColor: Hexcolor('#691b99'),
primaryColorLight: Hexcolor('#9b4dcb'),
primaryColorDark: Hexcolor('#37006a'),
secondaryHeaderColor: Hexcolor('#60C0D5'),
accentColor: Colors.deepOrange,
),
initialRoute: '/splash',
routes: {
'/splash': (context) => SplashScreen(),
'/login': (context) => Login(),
'/index': (context) => Index(),
'/settings': (context) => Settings(),
'/requests': (context) => Requests(),
'/add_request': (context) => AddRequest(),
'/request_comments': (context) => RequestComments(),
},
);
}
}
}
即使没有真正的互联网连接,它总是显示互联网应该工作的部分会发生什么。
【问题讨论】:
标签: android ios flutter dart get