Trying to check if a user is connected to the internet before i redirect them to the homepage. connectivity result shows as connectivity.wifi when am connected to the internet and returns true. but when i disconnect the internet on the emmulator it shows connectivity.none and returns true which still redirect the user to the homepage. i don’t want to direct the user to the homepage.
class SplashScreen extends StatefulWidget {
const SplashScreen({super.key});
@override
State<SplashScreen> createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
Future<bool> checkInternetConnectivity() async {
try {
final connectivityResult = await Connectivity().checkConnectivity();
print('Connectivity result: $connectivityResult');
return connectivityResult != ConnectivityResult.none;
} catch (e) {
print('Error checking connectivity: $e');
return false; // Assuming no connectivity in case of an error
}
}
this is the redirect code
void startTimer() {
Timer(Duration(seconds: 5), () async {
bool isConnected = await checkInternetConnectivity();
print('isConnected: $isConnected'); // Debug print
if (isConnected) {
if (await firebaseAuth.currentUser != null) {
firebaseAuth.currentUser != null
? AssistanceMethods.readCurrentUserOnlineInfo()
: null;
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (c) => MainScreen()));
} else {
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (c) => LoginScreen()));
}
} else {
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (c) => ErrorMsgScreen()));
}
});
}
2
Answers
To ensure the user is redirected to an error screen if there’s no internet connection, modify your checkInternetConnectivity method to correctly handle the connectivity status:
Make sure you have the connectivity_plus package added in your pubspec.yaml
As per the documentation here, the
connectivityResult
is a list and it should be used like this:So your
checkInternetConnnectivity()
method should be: