SlideShare a Scribd company logo
How to Validate Form With Flutter BLoC.pptx
How to Validate Form With Flutter BLoC?
One of the integral parts of many applications is form validation.
Mobile application developers always deal with the forms because it is
essential to show relevant warnings to the users whenever they do not
fill up the form correctly.
Developers need to do this task appropriately, and for that, they need
to write specific validation logic. Here, you will learn how to perform
form validation with flutter Bloc. Are you facing any trouble while
implementing this step and looking for an expert developer to perform
the form validation process correctly in your business application?
Then hire a Flutter developer from bosctechlabs.com today..
What does Flutter Bloc mean?
Flutter Bloc is the state management in Flutter. You can access it to handle all
the states you wish to perform in the flutter applications. It also acts as the
best and simplest way to do state management. It allows you to effortlessly
add any type of change to the flutter application.
Regardless of your level, you can learn the concept quickly and add this
dependency to your project. Google has created Bloc, which is nothing but
the design pattern assisting to separate business logic from the aware layer.
Additionally, it authorizes the developer to use the code efficiently.
Flutter Bloc has several widgets such as Bloc Builder, Bloc Selector, Bloc
provider, MultiBlocprovider, Bloc Listener, and Multi Bloc Listener. Every
widget performs a specific action, and thus you have to use the right one
suitable for your Flutter project.
How to do form validation in Flutter
The Flutter SDK renders the out-of-the-box widget and functionalities
to make the user’s lives easier while accessing form validation. Two
different approaches exist for form validation: the form widget and the
provider package. Here are the steps to follow to start form validation
in Flutter. Make sure you follow every step properly to get the desired
output.
• Create a form in Flutter; for instance, create a simple login page using
the fields such as email, password, phone number, and name.
• Set up the form to validate
• Input validation and input formatters
• Access Regex methods and Dart extension methods in the flutter
project
• You need to create the input fields required for the form.
• Make the custom form field.
• Perform form validation using provider, Bloc, or other techniques
Here, you will know in-depth about the Bloc because it is the best way
to validate the form. The bloc library renders the Flutter package for
validating the fields. It is commonly called form_bloc.
How to perform form validation using flutter Bloc
As soon as you implement form validation using flutter BLoC, you need
to add dependency in pubspec.ymal file to get all the properties of the
Bloc. As a result, you can use it for state management efficiently.
dependencies:
flutter:
sdk: Flutter
cupertino_icons: ^1.0.2
rxdart: ^0.27.3
flutter_bloc: ^8.0.1
Here, two dependencies rxdart and flutter_bloc are used. RxDart
extends the capabilities of the Stream controllers and Dart Streams.
Flutter_bloc is the use of Bloc Provider to render the Counter-cubit to
the Counter-page and then react to the state changes with the
BlocBuilder.
Create the cubit class (login_bloc_cubit.dart) for the app that is an
abstract class Cubit extends Bloc-base. Then, create the class by the
name LoginScreenCubit(). After that, define the argument constructor
and all the controllers you have used. Here is how it looks!
LoginScreenCubit() : super(LoginInitial());
//define controllers
final _userNameController = BehaviorSubject();
final _passwordController = BehaviorSubject();
final _phonenoController = BehaviorSubject();
You can obtain the data with the help of defined and stream controllers
like below mentioned.
Stream get userNameStream => _userNameController.stream;
Stream get passwordStream => _passwordController.stream;
Stream get phonenoStream => _phonenoController.stream;
Now, it is time to create the method for clearing the data. For that,
you can use the following code.
Then, add the methods for validation. It is one of the vital steps in the
entire project in which you can check the users’ value.
void dispose() {
updateUserName('');
updatePassword('');
updatePhoneNumber('');
}
//validation of UserName
voidupdateUserName(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");
}
}
Then, create the provider class (bloc_provider.dart) that passes all the
providers used in the Flutter application.
ListblocProviders = [
BlocProvider(create: (context) =>LoginPageCubit()),
];
Next, you need to wrap MaterialApp() with MultiBlocProvider() that
you define already in the bloc_provider.dart in main.
MultiBlocProvider(
providers: blocProviders,
child: constMaterialApp(
debugShowCheckedModeBanner: false,
home: LoginScreen(),
),
);
Then, create the class with the name “login_bloc_state.dart in which
you need to define LoginBloc{} and then LoginInitial that extends to
LoginBloc{}.
abstract class LoginBloc {}
classLoginInitial extends LoginBloc {}
Finally, in the LoginScreen(login_screen.dart), you must define
LoginScreenCubit and add initiState(){}. In that, you can add
WidgetsBinding.instance and access the dispose method properly.
LoginScreenCubit? _loginScreenCubit;
@override
void initState() {
WidgetsBinding.instance?.addPostFrameCallback((_) {
_loginScreenCubit?.dispose();
});
super.initState();
}
Finally, you need to add BlocProvider in _loginScreenCubit. It helps you
to get the right output of the login form with the values such as user
name, password, and phone number.
Create UI and access StreamBuilder for the text field to update the
data in the UI part properly. Here is the code to use.
_loginScreenCubit = BlocProvider.of(
context,
listen: false,
);
StreamBuilder(
stream: _loginScreenCubit?.passwordStream,
builder: (context, snapshot) {
returnTextField(
onChanged: (text) {
_loginScreenCubit?.updatePassword(text);
},
decoration: constInputDecoration(
labelText: 'Password',
),
keyboardType: TextInputType.text);
}),
When we run the application, we get the screen’s output like below.
How to Validate Form With Flutter BLoC.pptx
For Bottom Button 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 the login button is disable. When the
snapshot. data is true then the color of the button will be teal
otherwise it’s grey. Check out our guide to make floating action
button in FLutter.
_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),
),
),
),
);
},
);
}
How to Validate Form With Flutter BLoC.pptx
Conclusion
This blog demonstrated how to perform form validation in Flutter with
the help of Bloc. Besides, plenty of methods are there to do the same
things. It would help if you used the right technique suitable for your
Flutter project.
Source: https://bosctechlabs.com/validate-form-with-flutter-bloc/

More Related Content

PPTX
Presentaion on Dart and Flutter Development.pptx
PPTX
Introduction to Android Application Development with Flutter.pptx
PPTX
Dart presentation
PPTX
Flappy Birds Project
PPTX
Flutter introduction
PDF
Introduction to flutter
PPTX
Flutter introduction
PPTX
Introduction to flutter's basic concepts
Presentaion on Dart and Flutter Development.pptx
Introduction to Android Application Development with Flutter.pptx
Dart presentation
Flappy Birds Project
Flutter introduction
Introduction to flutter
Flutter introduction
Introduction to flutter's basic concepts

What's hot (20)

PPTX
PDF
Introduction to Spring Cloud
PPTX
Flutter presentation.pptx
PDF
Animations in Flutter
PPTX
GDSC Flutter Forward Workshop.pptx
PDF
Steamで同人ゲームをリリースする ~パブリッシャーになって検証してみた~
PDF
Press Button, Drink Coffee : An Overview of UE4 build pipeline and maintenance
PPTX
Flutter workshop
PPTX
Kubernetes 101
PPTX
Project onion - Project Architecture for .Net Core Application
PDF
Getting started with flutter
PPTX
Flutter frame work
PDF
Python과 Git으로 만드는 모바일 게임 패치 시스템
PDF
『DirectX 12를 이용한 3D 게임 프로그래밍 입문』 - 맛보기
PDF
Google flutter the easy and practical way
PDF
The magic of flutter
PDF
Domain Driven Design
PDF
flutter.school #HelloWorld
PPTX
Flutter talkshow
PPTX
What is Angular?
Introduction to Spring Cloud
Flutter presentation.pptx
Animations in Flutter
GDSC Flutter Forward Workshop.pptx
Steamで同人ゲームをリリースする ~パブリッシャーになって検証してみた~
Press Button, Drink Coffee : An Overview of UE4 build pipeline and maintenance
Flutter workshop
Kubernetes 101
Project onion - Project Architecture for .Net Core Application
Getting started with flutter
Flutter frame work
Python과 Git으로 만드는 모바일 게임 패치 시스템
『DirectX 12를 이용한 3D 게임 프로그래밍 입문』 - 맛보기
Google flutter the easy and practical way
The magic of flutter
Domain Driven Design
flutter.school #HelloWorld
Flutter talkshow
What is Angular?
Ad

Similar to How to Validate Form With Flutter BLoC.pptx (20)

PPTX
Mobile Application Development((Handling User Input and Navigation) class-05
PPTX
Mobile Application Development class 007
PDF
Bronx study jam 2
PDF
Flutter
PPTX
chapter 5.pptx
PDF
Flutter vs Java Graphical User Interface Frameworks.pptx
PDF
flutteragency-com-handling-events-and-user-input-in-flutter-.pdf
PDF
Form Validation in Flutter with Laravel Form Validation Syntax
PDF
iOS 개발자의 Flutter 체험기
PPTX
Flutter Road Map.pptx
PDF
Functional Reactive Programming - RxSwift
PPTX
Navigation_Rodsgaahfsfhsdfgsfhdfstjhfsuting.pptx
PPTX
Mobile Applications Development class 03-starting with flutter
PDF
InheritedWidget is your friend - GDG London (2018-08-08)
PDF
Flutter_GTU 8th Sem Gtu Format PPT for Presentation
PDF
Animations in Flutter - FlutterConf LATAM 2024
PPTX
ppt1.pptvadfbfsgndvnbgdnhgdmhjdzbcvxbfshfsxx
PPTX
CSE-4078 - Lecture - Week 10 -11aga.pptx
PDF
A Complete Guide to Building Your First App with Flutter
PPTX
TechCon Day - 5 App Dev
Mobile Application Development((Handling User Input and Navigation) class-05
Mobile Application Development class 007
Bronx study jam 2
Flutter
chapter 5.pptx
Flutter vs Java Graphical User Interface Frameworks.pptx
flutteragency-com-handling-events-and-user-input-in-flutter-.pdf
Form Validation in Flutter with Laravel Form Validation Syntax
iOS 개발자의 Flutter 체험기
Flutter Road Map.pptx
Functional Reactive Programming - RxSwift
Navigation_Rodsgaahfsfhsdfgsfhdfstjhfsuting.pptx
Mobile Applications Development class 03-starting with flutter
InheritedWidget is your friend - GDG London (2018-08-08)
Flutter_GTU 8th Sem Gtu Format PPT for Presentation
Animations in Flutter - FlutterConf LATAM 2024
ppt1.pptvadfbfsgndvnbgdnhgdmhjdzbcvxbfshfsxx
CSE-4078 - Lecture - Week 10 -11aga.pptx
A Complete Guide to Building Your First App with Flutter
TechCon Day - 5 App Dev
Ad

More from BOSC Tech Labs (20)

PDF
How Computer Vision Powers AI-Driven Process Optimization in Manufacturing.pdf
PDF
Top 10 Ways Computer Vision is Shaping Manufacturing Process.pdf
PDF
Top Computer Vision Opportunities and Challenges for 2024.pdf
PDF
How Computer Vision Is Changing the Entertainment Industry.pdf
PDF
How can Computer Vision help Manufacturers_.pdf
PDF
Machine Learning_ Advanced Computer Vision and Generative AI Techniques.pdf
PDF
What is Generative AI_ Unpacking the Buzz Around Generative AI Development Co...
PDF
20 Unexplored Use Cases for Generative AI in Customer Service.pdf
PDF
The Role of APIs in Custom Software Development for 2024
PDF
What is Generative AI for Manufacturing Operations_.pdf
PDF
How Gen AI Is Transforming The Customer Service Experience_.pdf
PDF
Transforming Visions into Reality with Generative AI.pdf
PDF
What is ChatGPT, DALL-E, and Generative AI_.pdf
PDF
All You Need To Know About Custom Software Development
PDF
The Most Impactful Custom Software Technologies of 2024
PDF
How Vision AI and Gen AI Can Drive Business Growth_.pdf
PDF
10 Detailed Artificial Intelligence Case Studies 2024 | BOSC TECH
PDF
Computer Vision in 2024 _ All The Things You Need To Know.pdf
PDF
GoRouter_ The Key to Next-Level Routing in Flutter Development.pdf
PDF
5 Key Steps to Successfully Hire Reactjs App Developers.pdf
How Computer Vision Powers AI-Driven Process Optimization in Manufacturing.pdf
Top 10 Ways Computer Vision is Shaping Manufacturing Process.pdf
Top Computer Vision Opportunities and Challenges for 2024.pdf
How Computer Vision Is Changing the Entertainment Industry.pdf
How can Computer Vision help Manufacturers_.pdf
Machine Learning_ Advanced Computer Vision and Generative AI Techniques.pdf
What is Generative AI_ Unpacking the Buzz Around Generative AI Development Co...
20 Unexplored Use Cases for Generative AI in Customer Service.pdf
The Role of APIs in Custom Software Development for 2024
What is Generative AI for Manufacturing Operations_.pdf
How Gen AI Is Transforming The Customer Service Experience_.pdf
Transforming Visions into Reality with Generative AI.pdf
What is ChatGPT, DALL-E, and Generative AI_.pdf
All You Need To Know About Custom Software Development
The Most Impactful Custom Software Technologies of 2024
How Vision AI and Gen AI Can Drive Business Growth_.pdf
10 Detailed Artificial Intelligence Case Studies 2024 | BOSC TECH
Computer Vision in 2024 _ All The Things You Need To Know.pdf
GoRouter_ The Key to Next-Level Routing in Flutter Development.pdf
5 Key Steps to Successfully Hire Reactjs App Developers.pdf

Recently uploaded (20)

PPTX
Operating system designcfffgfgggggggvggggggggg
PPTX
Why Generative AI is the Future of Content, Code & Creativity?
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PPTX
history of c programming in notes for students .pptx
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
PDF
iTop VPN Free 5.6.0.5262 Crack latest version 2025
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PPTX
Transform Your Business with a Software ERP System
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
top salesforce developer skills in 2025.pdf
PDF
System and Network Administration Chapter 2
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
Designing Intelligence for the Shop Floor.pdf
PPTX
Computer Software and OS of computer science of grade 11.pptx
Operating system designcfffgfgggggggvggggggggg
Why Generative AI is the Future of Content, Code & Creativity?
How to Choose the Right IT Partner for Your Business in Malaysia
history of c programming in notes for students .pptx
wealthsignaloriginal-com-DS-text-... (1).pdf
CHAPTER 2 - PM Management and IT Context
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
iTop VPN Free 5.6.0.5262 Crack latest version 2025
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Transform Your Business with a Software ERP System
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
top salesforce developer skills in 2025.pdf
System and Network Administration Chapter 2
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Designing Intelligence for the Shop Floor.pdf
Computer Software and OS of computer science of grade 11.pptx

How to Validate Form With Flutter BLoC.pptx

  • 2. How to Validate Form With Flutter BLoC? One of the integral parts of many applications is form validation. Mobile application developers always deal with the forms because it is essential to show relevant warnings to the users whenever they do not fill up the form correctly. Developers need to do this task appropriately, and for that, they need to write specific validation logic. Here, you will learn how to perform form validation with flutter Bloc. Are you facing any trouble while implementing this step and looking for an expert developer to perform the form validation process correctly in your business application? Then hire a Flutter developer from bosctechlabs.com today..
  • 3. What does Flutter Bloc mean? Flutter Bloc is the state management in Flutter. You can access it to handle all the states you wish to perform in the flutter applications. It also acts as the best and simplest way to do state management. It allows you to effortlessly add any type of change to the flutter application. Regardless of your level, you can learn the concept quickly and add this dependency to your project. Google has created Bloc, which is nothing but the design pattern assisting to separate business logic from the aware layer. Additionally, it authorizes the developer to use the code efficiently. Flutter Bloc has several widgets such as Bloc Builder, Bloc Selector, Bloc provider, MultiBlocprovider, Bloc Listener, and Multi Bloc Listener. Every widget performs a specific action, and thus you have to use the right one suitable for your Flutter project.
  • 4. How to do form validation in Flutter The Flutter SDK renders the out-of-the-box widget and functionalities to make the user’s lives easier while accessing form validation. Two different approaches exist for form validation: the form widget and the provider package. Here are the steps to follow to start form validation in Flutter. Make sure you follow every step properly to get the desired output.
  • 5. • Create a form in Flutter; for instance, create a simple login page using the fields such as email, password, phone number, and name. • Set up the form to validate • Input validation and input formatters • Access Regex methods and Dart extension methods in the flutter project • You need to create the input fields required for the form. • Make the custom form field. • Perform form validation using provider, Bloc, or other techniques Here, you will know in-depth about the Bloc because it is the best way to validate the form. The bloc library renders the Flutter package for validating the fields. It is commonly called form_bloc.
  • 6. How to perform form validation using flutter Bloc As soon as you implement form validation using flutter BLoC, you need to add dependency in pubspec.ymal file to get all the properties of the Bloc. As a result, you can use it for state management efficiently. dependencies: flutter: sdk: Flutter cupertino_icons: ^1.0.2 rxdart: ^0.27.3 flutter_bloc: ^8.0.1
  • 7. Here, two dependencies rxdart and flutter_bloc are used. RxDart extends the capabilities of the Stream controllers and Dart Streams. Flutter_bloc is the use of Bloc Provider to render the Counter-cubit to the Counter-page and then react to the state changes with the BlocBuilder. Create the cubit class (login_bloc_cubit.dart) for the app that is an abstract class Cubit extends Bloc-base. Then, create the class by the name LoginScreenCubit(). After that, define the argument constructor and all the controllers you have used. Here is how it looks!
  • 8. LoginScreenCubit() : super(LoginInitial()); //define controllers final _userNameController = BehaviorSubject(); final _passwordController = BehaviorSubject(); final _phonenoController = BehaviorSubject(); You can obtain the data with the help of defined and stream controllers like below mentioned. Stream get userNameStream => _userNameController.stream; Stream get passwordStream => _passwordController.stream; Stream get phonenoStream => _phonenoController.stream; Now, it is time to create the method for clearing the data. For that, you can use the following code.
  • 9. Then, add the methods for validation. It is one of the vital steps in the entire project in which you can check the users’ value. void dispose() { updateUserName(''); updatePassword(''); updatePhoneNumber(''); }
  • 10. //validation of UserName voidupdateUserName(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); } }
  • 11. //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"); } } Then, create the provider class (bloc_provider.dart) that passes all the providers used in the Flutter application. ListblocProviders = [ BlocProvider(create: (context) =>LoginPageCubit()), ];
  • 12. Next, you need to wrap MaterialApp() with MultiBlocProvider() that you define already in the bloc_provider.dart in main. MultiBlocProvider( providers: blocProviders, child: constMaterialApp( debugShowCheckedModeBanner: false, home: LoginScreen(), ), ); Then, create the class with the name “login_bloc_state.dart in which you need to define LoginBloc{} and then LoginInitial that extends to LoginBloc{}. abstract class LoginBloc {} classLoginInitial extends LoginBloc {}
  • 13. Finally, in the LoginScreen(login_screen.dart), you must define LoginScreenCubit and add initiState(){}. In that, you can add WidgetsBinding.instance and access the dispose method properly. LoginScreenCubit? _loginScreenCubit; @override void initState() { WidgetsBinding.instance?.addPostFrameCallback((_) { _loginScreenCubit?.dispose(); }); super.initState(); } Finally, you need to add BlocProvider in _loginScreenCubit. It helps you to get the right output of the login form with the values such as user name, password, and phone number.
  • 14. Create UI and access StreamBuilder for the text field to update the data in the UI part properly. Here is the code to use. _loginScreenCubit = BlocProvider.of( context, listen: false, );
  • 15. StreamBuilder( stream: _loginScreenCubit?.passwordStream, builder: (context, snapshot) { returnTextField( onChanged: (text) { _loginScreenCubit?.updatePassword(text); }, decoration: constInputDecoration( labelText: 'Password', ), keyboardType: TextInputType.text); }), When we run the application, we get the screen’s output like below.
  • 17. For Bottom Button 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 the login button is disable. When the snapshot. data is true then the color of the button will be teal otherwise it’s grey. Check out our guide to make floating action button in FLutter. _bottomButton() { return StreamBuilder( stream: _loginScreenCubit?.validateForm, builder: (context, snapshot) { return GestureDetector( onTap: () { if (snapshot.hasData) { Navigator.push( context, MaterialPageRoute(builder: (context) => Home1())); } },
  • 18. 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), ), ), ), ); }, ); }
  • 20. Conclusion This blog demonstrated how to perform form validation in Flutter with the help of Bloc. Besides, plenty of methods are there to do the same things. It would help if you used the right technique suitable for your Flutter project. Source: https://bosctechlabs.com/validate-form-with-flutter-bloc/