android - Connectivity package's onConnectionChanged() being called multiple times
问题描述
I have setup a basic check using Connectivity's Readme on checking internet connectivity.
@override
void initState() {
super.initState();
subscription = Connectivity()
.onConnectivityChanged
.listen((ConnectivityResult result) {
// Got a new connectivity status!
print("Check: $result");
});
}
@override
void dispose() {
print("Disposing Connection ...");
super.dispose();
subscription.cancel();
}
I haven't made any significant changes to the code itself. However, I when I checked the logs, It seems like the app is calling the function onConnectivityChanged()
twice, everytime a change in connection occurs.
Here are the logs:
Restarted application in 1,611ms.
I/flutter (17481): Check: ConnectivityResult.none
I/flutter (17481): Check: ConnectivityResult.mobile
I/flutter (17481): Check: ConnectivityResult.mobile
I/flutter (17481): Check: ConnectivityResult.none
I/flutter (17481): Check: ConnectivityResult.none
I/flutter (17481): Check: ConnectivityResult.wifi
I/flutter (17481): Check: ConnectivityResult.wifi
The first result is ConnectivityResult.none
and it appears only once. Because the app checks the connectivity only once when the current widget loads. However, after the first (correct) result, all the results are obtained twice, even though they should come out only once.
This has led to some complications in my app. Everytime I see a connection change, I show a dialog box to the user with the following options:
You are offline
You are on mobile network
But since the check somehow runs twice on connection changes, I have been seeing two dialog boxes. Not only that, since when I pop the dialog box out of the context, the app loads once again and does the check on initState()
causing the dialog box to show again. It will continue unless the phone is on WiFi, where there are no checks.
解决方案
推荐阅读
- reactjs - 在 React 中解析 json 字段
- html - 如何阻止我的表单在提交时重新加载?
- python - 我可以自动调整 pygame 中的文本大小以适应屏幕分辨率吗?
- c# - DataGridView 行选择器(记录选择器)实际上不选择
- javascript - 以 PDF 格式下载文件
- swift - SwiftUI AngularGradient 平滑过渡
- python - FileNotFoundError: [Errno 2] 没有这样的文件或目录。是的,路径存在,是的,我使用的是绝对路径
- mongodb - MongoDB聚合:如何添加一个嵌套字段,它是一个双重嵌套字段的总和?
- bash - 从多管道输出创建变量?
- python - 如何从索引中创建列?