To check the internet connection in a Flutter app, you can use the Connectivity
class from the flutter:connectivity
package. Here’s an example of how you might use this class to check the internet connection:
import 'package:flutter/material.dart'; import 'package:connectivity/connectivity.dart'; void main() { runApp(MyApp()); } class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { ConnectivityResult _connectionStatus; @override void initState() { super.initState(); checkInternetConnection(); } Future<void> checkInternetConnection() async { var connectivityResult = await Connectivity().checkConnectivity(); if (connectivityResult == ConnectivityResult.none) { setState(() { _connectionStatus = ConnectivityResult.none; }); } else { setState(() { _connectionStatus = connectivityResult; }); } } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: Center( child: _connectionStatus == ConnectivityResult.none ? Text('No internet connection') : Text('Internet connection is available'), ), ), ); } }
In this example, the checkInternetConnection
function is used to check the internet connection. It uses the Connectivity
class’s checkConnectivity
method to determine the current connectivity status, which can be either ConnectivityResult.none
(no internet connection) or one of the other ConnectivityResult
enum values (WiFi, mobile, or other). The function then updates the _connectionStatus
variable and calls setState
to rebuild the UI with the appropriate message.
Note that this example only checks the internet connection once, when the app first starts up. If you want to continuously monitor the internet connection and update the UI in real-time, you can use the Connectivity
class’s onConnectivityChanged
stream to receive updates whenever the connectivity status changes.