SlideShare a Scribd company logo
1 of 20
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.
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),
),
),
),
);
},
);
}
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

What's hot

Operator Overloading & Type Conversions
Operator Overloading & Type ConversionsOperator Overloading & Type Conversions
Operator Overloading & Type Conversions
Rokonuzzaman Rony
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
abhay singh
 
35787646 system-software-lab-manual
35787646 system-software-lab-manual35787646 system-software-lab-manual
35787646 system-software-lab-manual
Naveen Kumar
 
openFrameworks基礎 たくさんの図形を動かす 静的配列と動的配列 - 芸大グラフィックスプログラミング演習B
openFrameworks基礎 たくさんの図形を動かす 静的配列と動的配列 - 芸大グラフィックスプログラミング演習BopenFrameworks基礎 たくさんの図形を動かす 静的配列と動的配列 - 芸大グラフィックスプログラミング演習B
openFrameworks基礎 たくさんの図形を動かす 静的配列と動的配列 - 芸大グラフィックスプログラミング演習B
Atsushi Tadokoro
 

What's hot (20)

Operator Overloading & Type Conversions
Operator Overloading & Type ConversionsOperator Overloading & Type Conversions
Operator Overloading & Type Conversions
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
 
Access modifiers
Access modifiersAccess modifiers
Access modifiers
 
jQuery
jQueryjQuery
jQuery
 
Computer science Investigatory Project Class 12 C++
Computer science Investigatory Project Class 12 C++Computer science Investigatory Project Class 12 C++
Computer science Investigatory Project Class 12 C++
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
Server side rendering with React and Symfony
Server side rendering with React and SymfonyServer side rendering with React and Symfony
Server side rendering with React and Symfony
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 
Flutter
FlutterFlutter
Flutter
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Angular 2.0 Dependency injection
Angular 2.0 Dependency injectionAngular 2.0 Dependency injection
Angular 2.0 Dependency injection
 
Flask
FlaskFlask
Flask
 
Method overriding
Method overridingMethod overriding
Method overriding
 
35787646 system-software-lab-manual
35787646 system-software-lab-manual35787646 system-software-lab-manual
35787646 system-software-lab-manual
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlin
 
openFrameworks基礎 たくさんの図形を動かす 静的配列と動的配列 - 芸大グラフィックスプログラミング演習B
openFrameworks基礎 たくさんの図形を動かす 静的配列と動的配列 - 芸大グラフィックスプログラミング演習BopenFrameworks基礎 たくさんの図形を動かす 静的配列と動的配列 - 芸大グラフィックスプログラミング演習B
openFrameworks基礎 たくさんの図形を動かす 静的配列と動的配列 - 芸大グラフィックスプログラミング演習B
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutions
 
VTU Design and Analysis of Algorithms(DAA) Lab Manual by Nithin, VVCE, Mysuru...
VTU Design and Analysis of Algorithms(DAA) Lab Manual by Nithin, VVCE, Mysuru...VTU Design and Analysis of Algorithms(DAA) Lab Manual by Nithin, VVCE, Mysuru...
VTU Design and Analysis of Algorithms(DAA) Lab Manual by Nithin, VVCE, Mysuru...
 
Computer Science class 12
Computer Science  class 12Computer Science  class 12
Computer Science class 12
 
Threading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
Threading Made Easy! A Busy Developer’s Guide to Kotlin CoroutinesThreading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
Threading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
 

Similar to How to Validate Form With Flutter BLoC.pptx

Implementing Your Full Stack App with MongoDB Stitch (Tutorial)
Implementing Your Full Stack App with MongoDB Stitch (Tutorial)Implementing Your Full Stack App with MongoDB Stitch (Tutorial)
Implementing Your Full Stack App with MongoDB Stitch (Tutorial)
MongoDB
 
Flex In Portal Final
Flex In Portal   FinalFlex In Portal   Final
Flex In Portal Final
Sunil Patil
 
SH 2 - SES 1 - Stitch_Workshop_TLV.pptx
SH 2 - SES 1 - Stitch_Workshop_TLV.pptxSH 2 - SES 1 - Stitch_Workshop_TLV.pptx
SH 2 - SES 1 - Stitch_Workshop_TLV.pptx
MongoDB
 
Online bus pass registration
Online bus pass registrationOnline bus pass registration
Online bus pass registration
Yesu Raj
 

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

C#Portfolio
C#PortfolioC#Portfolio
C#Portfolio
 
User Forms & API integration
User Forms & API integrationUser Forms & API integration
User Forms & API integration
 
Implementing Your Full Stack App with MongoDB Stitch (Tutorial)
Implementing Your Full Stack App with MongoDB Stitch (Tutorial)Implementing Your Full Stack App with MongoDB Stitch (Tutorial)
Implementing Your Full Stack App with MongoDB Stitch (Tutorial)
 
Flex In Portal Final
Flex In Portal   FinalFlex In Portal   Final
Flex In Portal Final
 
How to implement sso using o auth in golang application
How to implement sso using o auth in golang applicationHow to implement sso using o auth in golang application
How to implement sso using o auth in golang application
 
Managed Extensibility Framework (MEF)
Managed Extensibility Framework (MEF)Managed Extensibility Framework (MEF)
Managed Extensibility Framework (MEF)
 
HTML5 Up and Running
HTML5 Up and RunningHTML5 Up and Running
HTML5 Up and Running
 
ASP.NET MVC3 RAD
ASP.NET MVC3 RADASP.NET MVC3 RAD
ASP.NET MVC3 RAD
 
Spring Framework-II
Spring Framework-IISpring Framework-II
Spring Framework-II
 
Better User Experience with .NET
Better User Experience with .NETBetter User Experience with .NET
Better User Experience with .NET
 
Subscribed zuora forsalesforce training -section301-final
Subscribed zuora forsalesforce training -section301-finalSubscribed zuora forsalesforce training -section301-final
Subscribed zuora forsalesforce training -section301-final
 
SH 2 - SES 1 - Stitch_Workshop_TLV.pptx
SH 2 - SES 1 - Stitch_Workshop_TLV.pptxSH 2 - SES 1 - Stitch_Workshop_TLV.pptx
SH 2 - SES 1 - Stitch_Workshop_TLV.pptx
 
MongoDB.local Atlanta: Introduction to Serverless MongoDB
MongoDB.local Atlanta: Introduction to Serverless MongoDBMongoDB.local Atlanta: Introduction to Serverless MongoDB
MongoDB.local Atlanta: Introduction to Serverless MongoDB
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Online bus pass registration
Online bus pass registrationOnline bus pass registration
Online bus pass registration
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
 
Code vauch
Code vauchCode vauch
Code vauch
 
Silverlight 2 for Developers - TechEd New Zealand 2008
Silverlight 2 for Developers - TechEd New Zealand 2008Silverlight 2 for Developers - TechEd New Zealand 2008
Silverlight 2 for Developers - TechEd New Zealand 2008
 
Login Project with introduction .pptx
Login Project with introduction .pptxLogin Project with introduction .pptx
Login Project with introduction .pptx
 
Vb6.0 intro
Vb6.0 introVb6.0 intro
Vb6.0 intro
 

More from BOSC Tech Labs

More from BOSC Tech Labs (20)

5 Key Steps to Successfully Hire Reactjs App Developers.pdf
5 Key Steps to Successfully Hire Reactjs App Developers.pdf5 Key Steps to Successfully Hire Reactjs App Developers.pdf
5 Key Steps to Successfully Hire Reactjs App Developers.pdf
 
How to set focus on an input field after rendering in ReactJS in 2024_.pdf
How to set focus on an input field after rendering in ReactJS in 2024_.pdfHow to set focus on an input field after rendering in ReactJS in 2024_.pdf
How to set focus on an input field after rendering in ReactJS in 2024_.pdf
 
How to Create Your First Android App Step by Step.pdf
How to Create Your First Android App Step by Step.pdfHow to Create Your First Android App Step by Step.pdf
How to Create Your First Android App Step by Step.pdf
 
How to Create Custom Animations in Flutter – A Step-by-Step Guide.pdf
How to Create Custom Animations in Flutter – A Step-by-Step Guide.pdfHow to Create Custom Animations in Flutter – A Step-by-Step Guide.pdf
How to Create Custom Animations in Flutter – A Step-by-Step Guide.pdf
 
How to create components in ReactJS_.pdf
How to create components in ReactJS_.pdfHow to create components in ReactJS_.pdf
How to create components in ReactJS_.pdf
 
Guide 101_ Material Design in Android App Development.pdf
Guide 101_ Material Design in Android App Development.pdfGuide 101_ Material Design in Android App Development.pdf
Guide 101_ Material Design in Android App Development.pdf
 
How do you hire a skilled Android developer for your project_.pdf
How do you hire a skilled Android developer for your project_.pdfHow do you hire a skilled Android developer for your project_.pdf
How do you hire a skilled Android developer for your project_.pdf
 
Guide to 2024’s Elite Software Developers by MobileAppDaily.pdf
Guide to 2024’s Elite Software Developers by MobileAppDaily.pdfGuide to 2024’s Elite Software Developers by MobileAppDaily.pdf
Guide to 2024’s Elite Software Developers by MobileAppDaily.pdf
 
How to build a live chat widget in React_.pdf
How to build a live chat widget in React_.pdfHow to build a live chat widget in React_.pdf
How to build a live chat widget in React_.pdf
 
React Best Practices All Developers Should Follow in 2024.pdf
React Best Practices All Developers Should Follow in 2024.pdfReact Best Practices All Developers Should Follow in 2024.pdf
React Best Practices All Developers Should Follow in 2024.pdf
 
How to hire ios app development experts for your next project_.pdf
How to hire ios app development experts for your next project_.pdfHow to hire ios app development experts for your next project_.pdf
How to hire ios app development experts for your next project_.pdf
 
Swiftui Vs Uikit_ Choosing the Right Ui Framework for ios Apps.pdf
Swiftui Vs Uikit_ Choosing the Right Ui Framework for ios Apps.pdfSwiftui Vs Uikit_ Choosing the Right Ui Framework for ios Apps.pdf
Swiftui Vs Uikit_ Choosing the Right Ui Framework for ios Apps.pdf
 
3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdf3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdf
 
The iOS Advantage_ How Apple’s Ecosystem Is Setting the Stage for Next-Gen Bu...
The iOS Advantage_ How Apple’s Ecosystem Is Setting the Stage for Next-Gen Bu...The iOS Advantage_ How Apple’s Ecosystem Is Setting the Stage for Next-Gen Bu...
The iOS Advantage_ How Apple’s Ecosystem Is Setting the Stage for Next-Gen Bu...
 
The Role iOS App Development_ Hiring for the Future.pdf
The Role iOS App Development_ Hiring for the Future.pdfThe Role iOS App Development_ Hiring for the Future.pdf
The Role iOS App Development_ Hiring for the Future.pdf
 
React 19: Revolutionizing Web Development
React 19: Revolutionizing Web DevelopmentReact 19: Revolutionizing Web Development
React 19: Revolutionizing Web Development
 
2024 Custom Software Development Guide: Trends, Steps & Benefits
2024 Custom Software Development Guide: Trends, Steps & Benefits2024 Custom Software Development Guide: Trends, Steps & Benefits
2024 Custom Software Development Guide: Trends, Steps & Benefits
 
What is the Easiest Way to Hire a React Developer?
What is the Easiest Way to Hire a React Developer?What is the Easiest Way to Hire a React Developer?
What is the Easiest Way to Hire a React Developer?
 
Top 10 React Carousel Component Libraries and their Usage Trends
Top 10 React Carousel Component Libraries and their Usage TrendsTop 10 React Carousel Component Libraries and their Usage Trends
Top 10 React Carousel Component Libraries and their Usage Trends
 
The Comprehensive Tech Guide to iOS Mobile App Development: From Concept to L...
The Comprehensive Tech Guide to iOS Mobile App Development: From Concept to L...The Comprehensive Tech Guide to iOS Mobile App Development: From Concept to L...
The Comprehensive Tech Guide to iOS Mobile App Development: From Concept to L...
 

Recently uploaded

Abortion Pills For Sale WhatsApp[[+27737758557]] In Birch Acres, Abortion Pil...
Abortion Pills For Sale WhatsApp[[+27737758557]] In Birch Acres, Abortion Pil...Abortion Pills For Sale WhatsApp[[+27737758557]] In Birch Acres, Abortion Pil...
Abortion Pills For Sale WhatsApp[[+27737758557]] In Birch Acres, Abortion Pil...
drm1699
 

Recently uploaded (20)

COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...
COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...
COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...
 
Anypoint Code Builder - Munich MuleSoft Meetup - 16th May 2024
Anypoint Code Builder - Munich MuleSoft Meetup - 16th May 2024Anypoint Code Builder - Munich MuleSoft Meetup - 16th May 2024
Anypoint Code Builder - Munich MuleSoft Meetup - 16th May 2024
 
OpenChain Webinar: AboutCode and Beyond - End-to-End SCA
OpenChain Webinar: AboutCode and Beyond - End-to-End SCAOpenChain Webinar: AboutCode and Beyond - End-to-End SCA
OpenChain Webinar: AboutCode and Beyond - End-to-End SCA
 
Abortion Pills For Sale WhatsApp[[+27737758557]] In Birch Acres, Abortion Pil...
Abortion Pills For Sale WhatsApp[[+27737758557]] In Birch Acres, Abortion Pil...Abortion Pills For Sale WhatsApp[[+27737758557]] In Birch Acres, Abortion Pil...
Abortion Pills For Sale WhatsApp[[+27737758557]] In Birch Acres, Abortion Pil...
 
Automate your OpenSIPS config tests - OpenSIPS Summit 2024
Automate your OpenSIPS config tests - OpenSIPS Summit 2024Automate your OpenSIPS config tests - OpenSIPS Summit 2024
Automate your OpenSIPS config tests - OpenSIPS Summit 2024
 
CERVED e Neo4j su una nuvola, migrazione ed evoluzione di un grafo mission cr...
CERVED e Neo4j su una nuvola, migrazione ed evoluzione di un grafo mission cr...CERVED e Neo4j su una nuvola, migrazione ed evoluzione di un grafo mission cr...
CERVED e Neo4j su una nuvola, migrazione ed evoluzione di un grafo mission cr...
 
Novo Nordisk: When Knowledge Graphs meet LLMs
Novo Nordisk: When Knowledge Graphs meet LLMsNovo Nordisk: When Knowledge Graphs meet LLMs
Novo Nordisk: When Knowledge Graphs meet LLMs
 
Your Ultimate Web Studio for Streaming Anywhere | Evmux
Your Ultimate Web Studio for Streaming Anywhere | EvmuxYour Ultimate Web Studio for Streaming Anywhere | Evmux
Your Ultimate Web Studio for Streaming Anywhere | Evmux
 
Abortion Pill Prices Mthatha (@](+27832195400*)[ 🏥 Women's Abortion Clinic In...
Abortion Pill Prices Mthatha (@](+27832195400*)[ 🏥 Women's Abortion Clinic In...Abortion Pill Prices Mthatha (@](+27832195400*)[ 🏥 Women's Abortion Clinic In...
Abortion Pill Prices Mthatha (@](+27832195400*)[ 🏥 Women's Abortion Clinic In...
 
Food Delivery Business App Development Guide 2024
Food Delivery Business App Development Guide 2024Food Delivery Business App Development Guide 2024
Food Delivery Business App Development Guide 2024
 
[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypse
[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypse[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypse
[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypse
 
Navigation in flutter – how to add stack, tab, and drawer navigators to your ...
Navigation in flutter – how to add stack, tab, and drawer navigators to your ...Navigation in flutter – how to add stack, tab, and drawer navigators to your ...
Navigation in flutter – how to add stack, tab, and drawer navigators to your ...
 
Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024
Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024
Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024
 
The mythical technical debt. (Brooke, please, forgive me)
The mythical technical debt. (Brooke, please, forgive me)The mythical technical debt. (Brooke, please, forgive me)
The mythical technical debt. (Brooke, please, forgive me)
 
Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024
 
architecting-ai-in-the-enterprise-apis-and-applications.pdf
architecting-ai-in-the-enterprise-apis-and-applications.pdfarchitecting-ai-in-the-enterprise-apis-and-applications.pdf
architecting-ai-in-the-enterprise-apis-and-applications.pdf
 
Software Engineering - Introduction + Process Models + Requirements Engineering
Software Engineering - Introduction + Process Models + Requirements EngineeringSoftware Engineering - Introduction + Process Models + Requirements Engineering
Software Engineering - Introduction + Process Models + Requirements Engineering
 
Lessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdfLessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdf
 
Weeding your micro service landscape.pdf
Weeding your micro service landscape.pdfWeeding your micro service landscape.pdf
Weeding your micro service landscape.pdf
 
Abortion Pill Prices Turfloop ](+27832195400*)[ 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Turfloop ](+27832195400*)[ 🏥 Women's Abortion Clinic in ...Abortion Pill Prices Turfloop ](+27832195400*)[ 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Turfloop ](+27832195400*)[ 🏥 Women's Abortion Clinic in ...
 

How to Validate Form With Flutter BLoC.pptx

  • 1.
  • 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.
  • 16.
  • 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), ), ), ), ); }, ); }
  • 19.
  • 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/