Flutter Connectivity Using StreamProvider
In mobile application development, developing apps based on the user network connectivity and also managing the app state is very important.
Let’s see how these challenges are effectively managed by connectivity plugin and provider plugin using flutter.
Before getting started, lets see what is connectivity and provider.
What is connectivity ?
It is a flutter plugin for discovering the state of the network (WiFi & mobile/cellular) connectivity on Android and iOS.
To know more about connectivity plugin, please refer here.
What is Provider ?
It is a dependency injection system built with widgets for widgets. provider
is mostly syntax sugar for InheritedWidget
, to make common use-cases straightforward.
If you are new to provider concept, please go through this.
Then, what is StreamProvider ?
It is a kind of provider that listen to a stream and expose the latest value emitted.
StreamProvider<T>.value(
value: // the stream with return type T.
child: // the widget to be built based on stream value.
)
Let’s begin the show :
Let’s create a flutter app and add dependencies to pubspec.yaml file.
Now create a class NetworkProvider which contains the stream subscription for listening connectivity changes and stream controller to add the latest value of connectivity change so that the widgets based on that stream controller will rebuild accordingly.
Now add a constructor to the class NetworkProvider which instantiate the stream controller and start listening to the connectivity changes.
Now create a widget (that takes instance of NetworkProvider as param) in our main.dart file that depends on the value returned by the stream controller in NetworkProvider class.
Finally, include our NetworkStatusBasedWidget inside the Scaffold ( the descendant of Provider that instantiate the NetworkProvider )
Conclusion:
Thank you for reading the article.You can find the source code for the above app from my GitHub.
Francium Tech is a technology company laser focused on delivering top quality software of scale at extreme speeds. Numbers and Size of the data don’t scare us. If you have any requirements or want a free health check of your systems or architecture, feel free to shoot an email to contact@francium.tech, we will get in touch with you!