Validation Using Bloc In Flutter
Hello Everyone! In this article, we learn about Bloc in Flutter. we cover many topics of the bloc like Bloc Widgets, Bloc Builder, Bloc Selector, Bloc Provider, Multi Bloc Provider, Bloc Listener, Multi Bloc Listener, etc…
If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.
Table Of Contents::
What Is Bloc?
Flutter Bloc is one of the state management in a flutter. We can use it to handle all the states which we want to perform in our flutter applications.
Bloc is the best and simple way to do state management. We can easily add any type of change to the Flutter application. You can easily learn the concept, no matter what’s your level. You can add this dependency to your project and use it.
Bloc is a design pattern created by Google to help separate business logic from the award layer and authorize a developer to exploit code more efficiently.
A state management library called Bloc was created and maintained by Felix Angelo. It assists developers utensil the Bloc design pattern in their Flutter application. It means that a developer must recognize the state of an app at some time. There should be something exhibited on the screen for every interplay with the app to let users know what is incident.
Bloc Widgets
There are many Wiglets in Flutter Bloc:
> Bloc Builder:
Bloc-builder is a Flutter widget that needs a bloc and a builder function. Bloc-builder holds building the widget in response to new states. Bloc-builder is very alike to Stream-builder but has a more simple API to decrease the quantity of boilerplate code needed. The builder function will potentially be called many times and should be an unalloyed function that returns a widget in reaction to the state.
BlocBuilder<BlocA, BlocAState>(
builder: (context, state) {
// return widget here based on BlocA's state
}
)
> Bloc Selector:
Bloc-selector is a Flutter widget that is comparable to BlocBuilder but permits developers to filter modernize by selecting a new worth based on the contemporary bloc state. dispensable builds are averted if the selected value does not switch. The pick value must be fixed for Bloc Selector to correctly control whether the builder should be called again.
BlocSelector<BlocA, BlocAState, SelectedState>(
selector: (state) {
// return selected state based on the provided state.
},
builder: (context, state) {
// return widget here based on the selected state.
},
)
> Bloc Provider:
Bloc Provider is a Flutter widget that provides a bloc to its children via BlocProvider.of<T>(context). It is worn as a dependency injection (DI) widget to bestow a lone instance of a bloc to beau-coup widgets within a sub-tree.
BlocProvider(
create: (BuildContext context) => BlocA(),
child: ChildA(),
);
> MultiBlocProvider:
Multi Bloc Provider is a Flutter widget that amalgamates multiple Bloc Provider widgets into one. MultiBlocProvider better the readability and removes the need to nest multipleBlocProviders.
BlocProvider<BlocA>(
create: (BuildContext context) => BlocA(),
child: BlocProvider<BlocB>(
create: (BuildContext context) => BlocB(),
child: BlocProvider<BlocC>(
create: (BuildContext context) => BlocC(),
child: ChildA(),
)
)
)
> Bloc Listener:
Bloc Listener is a Flutter widget that clasps a BlocWidgetListener and a voluntary bloc and invokes the listeners in response to state swap in the bloc. It should be worn for functionality that needs to happen once per state change such as navigation, showing a Snack-bar, showing a Dialog, etc…
BlocListener<BlocA, BlocAState>(
listener: (context, state) {
// do stuff here based on BlocA's state
},
child: Container(),
)
> Multi Bloc Listener:
Multi Bloc Listener is a Flutter widget that amalgamates multiple BlocListener widgets into one. MultiBlocListener better the readability and eliminates the requirement to nest multipleBlocListeners. By utilizing multipleBlocListener we can go from:
BlocListener<BlocA, BlocAState>(
listener: (context, state) {},
child: BlocListener<BlocB, BlocBState>(
listener: (context, state) {},
child: BlocListener<BlocC, BlocCState>(
listener: (context, state) {},
child: ChildA(),
),
),
)
Implementation:
First, we have to add dependency in pubspec.ymal file for getting all the properties of the bloc by which we can easily use it for state management.
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
rxdart: ^0.27.3
flutter_bloc: ^8.0.1
We use two dependencies flutter_bloc and rxdart. RxDart extends the capabilities of Dart Streams and Stream-controllers. Flutter_bloc uses Bloc Provider to provide a Counter-cubit to a Counter-Page and react to state changes with BlocBuilder.
First, we have to create a cubit class(login_bloc_cubit.dart) for the app which is an abstract class Cubit extends Bloc-base. We create the class by the name LoginScreenCubit(). In this class first, we have to define the argument constructor. After that, we define all the controllers which we used.
LoginScreenCubit() : super(LoginInitial());
//define controllers
final _userNameController = BehaviorSubject<String>();
final _passwordController = BehaviorSubject<String>();
final _phonenoController = BehaviorSubject<String>();
and we get the data with the help of Stream and defined controllers.
Stream<String> get userNameStream => _userNameController.stream;
Stream<String> get passwordStream => _passwordController.stream;
Stream<String> get phonenoStream => _phonenoController.stream;
we also create a method for clearing the data
void dispose() {
updateUserName('');
updatePassword('');
updatePhoneNumber('');
}
and add the methods for validation which is very important and in which we check the value of the user.
//validation of UserName
void updateUserName(String userName) {
if (userName.length < 3) {
_userNameController.sink.addError("Please enter at least 3 words");
} else {
_userNameController.sink.add(userName);
}
}
//validation of Password
void updatePassword(String password) {
if (password.length < 4) {
_passwordController.sink.addError("Please enter more then 4 words");
} else {
_passwordController.sink.add(password);
}
}
//validation of Phone Number
void updatePhoneNumber(String phoneNo) {
if (phoneNo.length == 10) {
_phonenoController.sink.add(phoneNo);
} else {
_phonenoController.sink.addError("Please enter valid Phone Number");
}
}
After that, we create a provider class(bloc_provider.dart) in which we pass all the providers which are used in the Flutter application.
List<BlocProvider> blocProviders = [
BlocProvider<LoginPageCubit>(create: (context) => LoginPageCubit()),
];
And wrap MaterialApp() with MultiBlocProvider(), which we already define in the bloc_provider.dart in main. dart class. And pass the bloc Provider in providers.
MultiBlocProvider(
providers: blocProviders,
child: const MaterialApp(
debugShowCheckedModeBanner: false,
home: LoginScreen(),
),
);
And create a class with the name of login_bloc_state.dart. In which we define the LoginBloc{} class and LoginInitial which extends to LoginBloc{}.
abstract class LoginBloc {}
class LoginInitial extends LoginBloc {}
In the LoginScreen(login_screen.dart) First we define the LoginScreenCubit. And then add initState(){} in which we add WidgetsBinding.instance and the use dispose method.
LoginScreenCubit? _loginScreenCubit;
@override
void initState() {
WidgetsBinding.instance?.addPostFrameCallback((_) {
_loginScreenCubit?.dispose();
});
super.initState();
}
In _loginScreenCubit, we add BlocProvider.
_loginScreenCubit = BlocProvider.of<LoginScreenCubit>(
context,
listen: false,
);
When we run the application, we ought to get the screen’s output like the underneath screen capture.
In the UI part, we create UI and use StreamBuilder for the text Field to update the data.
StreamBuilder(
stream: _loginScreenCubit?.passwordStream,
builder: (context, snapshot) {
return TextField(
onChanged: (text) {
_loginScreenCubit?.updatePassword(text);
},
decoration: const InputDecoration(
labelText: 'Password',
),
keyboardType: TextInputType.text);
}),
When we run the application, we ought to get the screen’s output like the underneath screen capture.
For Bottombutton we also use StreamBuilder. In this we pass _loginScreenCubit in the stream and cheBloc Widgetsck, whether the data is validated or not? after this we return GestureDetector() and apply a condition that if the data is updated then this screen goes to the next screen otherwise it’s showing an error. When the snapshot. data is true then the color of the button will be teal otherwise it’s grey.
_bottomButton() {
return StreamBuilder(
stream: _loginScreenCubit?.validateForm,
builder: (context, snapshot) {
return GestureDetector(
onTap: () {
if (snapshot.hasData) {
Navigator.push(
context, MaterialPageRoute(builder: (context) => Home1()));
}
},
child: Container(
decoration: BoxDecoration(
color: snapshot.hasData ? Colors.teal : Colors.grey,
borderRadius: BorderRadius.circular(30)),
height: 70,
width: MediaQuery.of(context).size.width,
child: const Center(
child: Text(
'Login',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 27),
),
),
),
);
},
);
}
When we run the application, we ought to get the screen’s output like the underneath screen capture.
Conclusion:
In this article, we have been through What is Bloc in Flutter along with how to implement it in a Flutter. By using we can perform many state management orations.
❤ ❤ Thanks for reading this article ❤❤
If I got something wrong? Let me know in the comments. I would love to improve.
Clap 👏 If this article helps you.
GitHub Link:
Find the source code of the Validation Using Bloc In Flutter:
GitHub – flutter-devs/validation_using_bloc
You can’t perform that action at this time. You signed in with another tab or window. You signed out in another tab or…github.com
Feel free to connect with us:
And read more articles from FlutterDevs.com.
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter-related queries.
We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.