This is the code i use to check for internet connectivity in flutter
import 'dart:async';
import 'package:internet_connection_checker/internet_connection_checker.dart';
import 'package:flutter/material.dart';
class CheckingConnectivity {
late InternetConnectionChecker internetConnectionChecker;
late StreamSubscription<InternetConnectionStatus> connectionStatusListener;
bool hasInternetConnection = false;
var onStatusChange = InternetConnectionChecker().onStatusChange;
//Checking Internet connection
internetChecker(BuildContext context) async {
var connectionChanging = onStatusChange.listen((event) async {
hasInternetConnection = event == InternetConnectionStatus.connected;
if(hasInternetConnection == true) {
showSnackBar(context, "Connected");
} else if(hasInternetConnection == false) {
showSnackBar(context, "Disconnected");
}
});
}
showSnackBar(BuildContext context, String message) {
final snackBar = SnackBar(content: Text(message,
style: TextStyle(color: Colors.white, backgroundColor: Colors.grey),));
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
}
When the application launches, it shows connected even when i am already connected to the internet. I want it to show connected only when i reconnect to the internet. Thank you very much. I appreciate
So, when looking through the library's code, I see that they initially always send a status update. A simple workaround would be to have a counter variable that increments every time you receive a status change event. If the counter variable has its default value, you know you received the initial event.