Flutter is most popular infant in the mobile application and cross platform application development world. Flutter is small in age but very big and vast in term of features, and this is the big reason every mobile application developer is adopting flutter development. Flutter have very large number of libraries and plugins available to use, and with the help of these plugins flutter development become very fast and easy. The most popular package or plugin these days is Flutter Getx. Getx is multiple purpose plugins have lot of tools inside it, but the most demanding and useable feature is state management.
State management is the soul of every application and we can think to make any feature without managing the state of our widgets. In this tutorial we are not going to cover definition or introduction of Getx, if you want to read more about it you can click on this this link and if sitll looking for more simple and practical introduction to understand it more deeply leave your comments down, so that i can make a new post specifically on the introduction of Flutter Getx.
In today tutorial we will learn about how to get internet state in real time, with using of Getx and Connectivity Plus package. In our app we often need to check internet in real time, and have to run some events on the basis of internet connectivity. Most of the people are doing it with the help of stream, which is also a very good way, but as we have power of Getx simplicity then it is good if we can do lot of things with less code and off-course in easy and reusable way.
Please Note- In this tutorial i am not going through the basics of Getx, not covering how to define variables, how to updating the values because I am considering as you are already know about these things.
What we will get in output?
Required Dependencies
get:
connectivity_plus:
Let’s start step by step implementation so that we can understand what is need to be done to achieve the desired output. First we will convert our whole app which MaterialApp to GetMatrialApp so that we can use Getx as global context in our app.
return GetMaterialApp(
initialBinding: ControllerBinding(),
title: 'Internet Connectivity Check (Using Getx)',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomeScreen(),
);
Second we will make Getx Controller class, in this class we will code all the events related to flutter internet connectivity, and these events will later bind with our widgets with the help of Getx Obx widget. Getx Obx is like a listener who react every time when there is any change in Getx variable without affecting other widgets of the class, which if called state management.
connection_manager_controller.dart
import 'dart:async';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import '../helper.dart';
class ConnectionManagerController extends GetxController {
//0 = No Internet, 1 = WIFI Connected ,2 = Mobile Data Connected.
var connectionType = 0.obs;
final Connectivity _connectivity = Connectivity();
late StreamSubscription _streamSubscription;
@override
void onInit() {
super.onInit();
getConnectivityType();
_streamSubscription =
_connectivity.onConnectivityChanged.listen(_updateState);
}
Future<void> getConnectivityType() async {
late ConnectivityResult connectivityResult;
try {
connectivityResult = await (_connectivity.checkConnectivity());
} on PlatformException catch (e) {
if (kDebugMode) {
print(e);
}
}
return _updateState(connectivityResult);
}
_updateState(ConnectivityResult result) {
switch (result) {
case ConnectivityResult.wifi:
connectionType.value = 1;
break;
case ConnectivityResult.mobile:
connectionType.value = 2;
break;
case ConnectivityResult.none:
connectionType.value = 0;
break;
default:
showSnackBar(title: 'Error', message: 'Failed to get connection type');
break;
}
}
@override
void onClose() {
_streamSubscription.cancel();
}
}
Getx Binding
When we create a Getx controller then we need to call it, there are two ways of calling, 1 is with the help of binding and 2 is without binding. But in our tutorial we are using bindings so that we can use full power of Getx, and can do task in proper way.
controller_binding.dart
import 'package:get/get.dart';
import 'package:getx_internet_connectivity/getx/connection_manager_controller.dart';
class ControllerBinding extends Bindings {
@override
void dependencies() {
Get.lazyPut<ConnectionManagerController>(
() => ConnectionManagerController());
}
}
Now we will call this binding on app loading in memory, it means when we will open our then firstly main method will call runapp function which will call our GetMaterialApp widget. In this GetMaterialApp widget we will call our binding, check the example given below.
my_radio_button_widget.dart
return GetMaterialApp(
initialBinding: ControllerBinding(), //controller bind here
title: 'Internet Connectivity Check (Using Getx)',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomeScreen(),
);
Till here have almost done all logic part, with the help of Getx Controller and Getx Binding, Now let’s move to our screen where we want to make our widgets reactive with internet connectivity in real time. It is very simple and matter of just a few lines.
home_screen.dart
Consider this class as your class where you need to use internet connectivity events. Obx is a reactive widget, who will listen all the changes on variable connectionType, whenever connectionType variable will be modified then it will receive a call, and as per the value, child widgets will get updated.
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_internet_connectivity/getx/connection_manager_controller.dart';
class HomeScreen extends StatelessWidget {
HomeScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final ConnectionManagerController _controller =
Get.find<ConnectionManagerController>();
return Scaffold(
appBar: AppBar(
title: const Text('Internet Connection Check Using Getx'),
),
body: Center(
child: Obx(() => Text(
_controller.connectionType.value == 1
? "Wifi Connected"
: _controller.connectionType.value == 2
? 'Mobile Data Connected'
: 'No Internet',
style: const TextStyle(fontSize: 20),
)),
),
);
}
}
If you have any query feel free to ask. Also, check out the bottom navigation series, custom textfield, custom social login buttons and many others.
You can download full code.