Implement BLoC Pattern With TextField

In this post we will learn to implement BLoC pattern with TextField of a Flutter app. We will use also use StreamController to receive user input and StreamHandler to show an error message if input is not valid.

Introduction

BLoC pattern is the preferred State Management pattern when developing mobile apps with Flutter. If you are completely new to BLoC pattern, you should checkout our other post on BLoC pattern with flutter.

Basically a BLoC pattern encourages separation of business logic from the user interface layer.

In this post we will create a TextField and handle it’s onChanged event using a stream controller implementing the BLoC pattern.

Setup

Let’s start off by creating a Flutter Material app with a single TextField.

We have added some basic InputDecoration on this TextField as well.

See our previous post about learning to decorate a TexField here.

The output for the code above:

Single TextField
Single TextField

Setup A BLoC For The TextField

A BLoC is nothing but just another class. We will create a class named TextBloc which will look like this:

This class has couple of things:

  1. StreamController
    • This is responsible for adding data and error events on it’s stream.
  2. Stream
    • Stream of string data.

Now to add data to the stream controller, we will also need a public function.

Implementing BLoC With TextField

Now we can use the TextBloc in our app by first creating an instance of this bloc and using the updateText method during the onChanged event.

As you can see, whenever a user enters value for the TextField, this value gets passed onto the StreamController inside our BLoC.

Become A Flutter Expert With This Course

Showing Errors On TextField

Now that we have a working BLoC for our TextField, next we want to show errors whenever user enters invalid values.

In order to achieve this, we will have to listen to the text stream for the data entered by the user. For this purpose, we will make use of the StreamBuilder widget.

Final Output:

Showing Error On TextField
Showing Error On TextField

About the author