Flutterexperts

Empowering Vision with FlutterExperts' Expertise
Network State Handling like Kotlin Sealed classes | Flutter

In the article, I’ll be showing you how you can manage the state of the network just like kotlin sealed classes.

if you want to know about the kotlin sealed classes check out

Is sealed class also supported in dart?

NO , sealed classes are not supported in dart.

How can we use the same in dart?

Yes, there is an alternative in dart .
You must have heard of provider package in flutter for state management, Remi has done great work, do you know he also has create another package which is freezed.

freezed | Dart Package
Welcome to Freezed, yet another code generator for unions/pattern-matching/copy. While there are many code-generators…pub.dev

Let’s see how can we achieve network state handling just like kotlin sealed classes

Step 1: Install the dependency

dependencies: 
freezed: <latest-version>

and

dev_dependencies:
build_runner: <latest-version>

now run pub get

Step 2: Create a network state class

Before creating the network state class we need to see what states do we need?

We will need Success, Error, Loading, Idle states.

https://gist.github.com/ashishrawat2911/de6237ed6d5eea29e1fbf6c541bcb441#file-result-dart

Create a freezed class and define the states, If you see we have created the Result class generic so it can we used for any data. We only want data to in Result.success() and reason for failure in Result.failure() .

Now freezed will generate file , for that you need to specify

part 'result.freezed.dart';

Now run

flutter packages pub run build_runner build 

Your generated will look like this

https://gist.github.com/ashishrawat2911/d15863bfdfe109241b65706b3ffe76fd#file-result-freezed-dart

Now we will be using it with streams (Bloc)

Step 3: Create a bloc class

Create a stream controller with the data type you what encapsulated with Result class you have generated.

StreamController<Result<List<Prediction>>> streamController =      StreamController<Result<List<Prediction>>>();

Create the method which will do the API handling, initial you will need to add loading into the stream so the UI will begin to load

streamController.sink.add(Result.loading());

now hit the API,

try {

Prediction prediction = await appRepository.getPlacesPrediction(search);
//Do something when you get the data

} catch (e) {
// When you get an exception
}

If you get the result

streamController.sink.add(Result.success(data: prediction.predictionsList));

On error, you will add the

streamController.sink.add(Result.failure(reason: e.toString()));

You can do an error handling on you own to display your own error.

See the bloc class here

https://gist.github.com/ashishrawat2911/f5dfdecf685908a4dfad4eb54d8bb497#file-prediction_bloc-dart

Step 4: Update the UI

First, we need to create the bloc instance

PlacePredictionSearchBloc placePredictionSearchBloc = PlacePredictionSearchBloc();

Now use the StreamBuilder

StreamBuilder<Result<List<Prediction>>>(

stream: placePredictionSearchBloc.streamController.stream,

initialData: Result.idle(),

builder: (BuildContext context,
AsyncSnapshot<Result<List<Prediction>>> snapshot) {

return snapshot.data.when(idle: () {

}, loading: () {

}, success: (List<Prediction> value) {

}, failure: (String reason) {

});
},
),

Now you can we can manage the UI according to the network state.
In the initialData parameter, I have provided the Result.Idle so in the starting whatever we pass in the idle :(){} will show into UI

Check the code here

https://gist.github.com/ashishrawat2911/4892e72602204c34fade8b874ca15ede#file-result_stream_builder-dart

Thanks for reading this article

If I got something wrong, Let me know in the comments. I would love to improve.

Connect with me https://www.ashishrawat.dev


And read more articles from FlutterDevs.com

FlutterDevs has been working on Flutter from quite some time now. You can connect with us on Facebook and Twitter for any flutter related queries.

We welcome feedback and hope that you share what you’re working on using #Flutter. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!

Leave comment

Your email address will not be published. Required fields are marked with *.