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.
initState()
twice. Is this normal behaviour? Should I add a bug report to flutter's github? – ErminainitState()
is being called multiple times? or are you talking about other functions? – Erminaflutter
is developed by design and IMHO we can't change it, otherwise, something else might break. AlthoughinitState(){}
is called only once. I can't wrap my head around it either, but you should be better off subscribing to connectivity in the first screen itself. Good luck and Happy Coding :) – Ermina