How can we check internet connectivity? I can check with Streambuilder but how to achieve this with routers? The problem is we can not use async await in this.
If anyone can suggest anything on this will be much appreciated. OnGenerateRoute we can check the provided route. As in code, I passed the _connectivityStatus to check and route to no internet screen but that is not working.
class MyProjectAppScreen extends ConsumerStatefulWidget {
const MyProjectAppScreen({super.key});
@override
ConsumerState<MyProjectAppScreen> createState() {
return _MyProjectAppScreenState();
}
}
class _MyProjectAppScreenState extends ConsumerState<MyProjectAppScreen> {
ConnectivityResult _connectionStatus = ConnectivityResult.none;
final Connectivity _connectivity = Connectivity();
late StreamSubscription<ConnectivityResult> _connectivitySubscription;
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initConnectivity() async {
late ConnectivityResult result;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
result = await _connectivity.checkConnectivity();
} on PlatformException catch (e) {
developer.log('Couldn\'t check connectivity status', error: e);
return;
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) {
return Future.value(null);
}
return _updateConnectionStatus(result);
}
Future<void> _updateConnectionStatus(ConnectivityResult result) async {
print(result);
setState(() {
_connectionStatus = result;
});
}
@override
void initState() {
initConnectivity();
_connectivitySubscription =
_connectivity.onConnectivityChanged.listen(_updateConnectionStatus);
super.initState();
}
@override
Widget build(BuildContext context) {
String appRoot = splash;
return MaterialApp(
title: 'My Project',
theme: theme_data.ManageTheme().getTheme(context),
darkTheme: theme_data.ManageTheme().getDarkTheme(context),
themeMode: ThemeMode.light,
initialRoute: appRoot,
onGenerateRoute: (settings) => generateRoute(settings, _connectionStatus),
debugShowCheckedModeBanner: false,
);
}
}
How to achieve this in globally?
I am able to display a
No Internetscreen whenever there is no internet with this code. Additionally, I have added a few TODO statements, please review them.