Reputation: 1600
I'm looking to add an 'Internet connection checker' to my Flutter app (i.e. web & Android), but there would seem to be a contradiction between where the typical internet connection checker widget is inserted (i.e. the home page) and the fact that my 'main' class includes a number of setup calls made before the 'runApp' step that depend on internet connection, e.g. initialising Supabase.
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final aPrefs = await SharedPreferences.getInstance();
await SupabaseUtil.init();
await GdSubscriptionService.init();
runApp(
ProviderScope(
overrides: [
sharedPrefsProvider.overrideWithValue(aPrefs),
],
child: const MyApp(),));
}
Wouldn't it make more sense to set the internet connection checking at the start of the main class code?
Any suggestions?
Upvotes: 0
Views: 62
Reputation: 340
You can create class with a function to check connectivity, something like this
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:voters_app/widgets/shared/toast_service.dart';
class NetworkUtils {
static Future<bool> checkInternetConnection() async {
final connectivityResult = await Connectivity().checkConnectivity();
if (connectivityResult.contains(ConnectivityResult.none)) {
// print or show toast to inform user that there is no internet connection.
return false;
}
return true;
}
}
I am using this flutter package Connectivity_plus You can check at the main.dart the connection and do whatever you want by the return. also I recommend you to use state manager to handle this.
Upvotes: 1