Today's article will show you how to check the Internet connection in Flutter apps. For example, if you build an app with many resources that are coming from the internet, what happens if the internet disappears? We will solve this problem in this article, so let's get to work before getting carried away.
For this app I am using GetX architect, If you don’t know much about GetX you can check out the below article.
Article: How To Create The Flutter App With Getx Architect
The first step is to install these dependencies in your pubspec.yaml file.
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
get: ^4.6.1
flutter_svg: ^1.0.0
data_connection_checker:
git:
url: https://github.com/chornthorn/data_connection_checker.git
ref: master
Here is a simple counter app I made with Flutter and GetX architect. Our next task is to add internet connection checking to it. To do that, we need to follow a few steps.
STEP 1
Create your app structure like the below image.
STEP 2
Now create the home page and routes.
//home/home_controller.dart
import 'package:get/get.dart';
class HomeController extends GetxController {
int counter = 0;
void incrementCounter() {
counter++;
update(); //update method is nothing but setState
}
}
//home/home_binding.dart
import 'package:get/get.dart';
import 'package:internet_connection_checker/home/home_page_controller.dart';
class HomeBinding extends Bindings {
@override
void dependencies() {
Get.lazyPut(() => HomeController());
}
}
//home/home_page.dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:internet_connection_checker/home/home_page_controller.dart';
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return GetBuilder<HomeController>(
builder: (controller) => Scaffold(
appBar: AppBar(
title: Text('Counter App'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'${controller.counter}',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: controller.incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
),
);
}
}
//routes/app_routes.dart
class AppRoutes {
static const home = '/home';
}
//routes/app_pages.dart
import 'package:get/get.dart';
import 'package:internet_connection_checker/home/home_page.dart';
import 'package:internet_connection_checker/home/home_page_binding.dart';
import 'package:internet_connection_checker/routes/app_routes.dart';
class AppPages {
static final List<GetPage> pages = [
GetPage(
name: AppRoutes.home,
page: () => HomePage(),
binding: HomeBinding(),
),
];
}
STEP 3
Create a widget that will appear when the Internet connection is lost.
//widget/network_error_item.dart
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
class NetworkErrorItem extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
height: Get.height, //Get.height = MediaQuery.of(context).size.height
width: Get.width, //Get.width = MediaQuery.of(context).size.width
color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
//Here I am using an svg icon
SvgPicture.asset(
'assets/icons/network.svg',
width: 200,
height: 200,
color: Colors.red[200],
),
const SizedBox(height: 30),
const Text(
'Internet connection lost!',
style: TextStyle(fontSize: 16, color: Colors.grey),
),
const Text(
'Check your connection and try again.',
style: TextStyle(fontSize: 16, color: Colors.grey),
)
],
),
),
);
}
}
STEP 4
Now create a network status service that will check if the device is connected to the internet. Whenever the Internet is connected, it will redirect to the home page, otherwise, it will show the Internet connection has been lost.
//services/network_status_service.dart
import 'package:data_connection_checker/data_connection_checker.dart';
import 'package:get/get.dart';
import 'package:internet_connection_checker/routes/app_routes.dart';
import 'package:internet_connection_checker/widgets/network_error_item.dart';
class NetworkStatusService extends GetxService {
NetworkStatusService() {
DataConnectionChecker().onStatusChange.listen(
(status) async {
_getNetworkStatus(status);
},
);
}
void _getNetworkStatus(DataConnectionStatus status) {
if (status == DataConnectionStatus.connected) {
_validateSession(); //after internet connected it will redirect to home page
} else {
Get.dialog(NetworkErrorItem(), useSafeArea: false); // If internet loss then it will show the NetworkErrorItem widget
}
}
void _validateSession() {
Get.offNamedUntil(AppRoutes.home, (_) => false); //Here redirecting to home page
}
}
STEP 5
Create the dependencies injection class that will call the network status service class.
//utils/dependency_injection.dart
import 'package:get/get.dart';
import 'package:internet_connection_checker/services/network_status_service.dart';
class DependencyInjection {
static void init() async {
//services
Get.put<NetworkStatusService>(NetworkStatusService(), permanent: true);
}
}
STEP 6
Now call the dependencies injection class in the void main class.
//main.dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:internet_connection_checker/home/home_page.dart';
import 'package:internet_connection_checker/home/home_page_binding.dart';
import 'package:internet_connection_checker/routes/app_pages.dart';
import 'package:internet_connection_checker/utils/dependency_injection.dart';
void main() {
runApp(const MyApp());
DependencyInjection.init(); //Here we are calling the Dependency Injection
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return GetMaterialApp(
debugShowCheckedModeBanner: false,
title: 'Counter App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomePage(),
initialBinding: HomeBinding(),
getPages: AppPages.pages,
);
}
}
All is done, now build your app. After it has been successfully built, disconnect your device from the internet.
You can download the source code from the GitHub repository.
Conclusion
Thus, we learned in detail in this article how you can check the internet connectivity in Flutter apps using the data_connection_checker
package.
I hope you like this article.
The article is sponsored by: UniqueApps
Top comments (0)