SlideShare une entreprise Scribd logo
1  sur  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/

Contenu connexe

Tendances

Flutter: Future of App Development
Flutter: Future of App DevelopmentFlutter: Future of App Development
Flutter: Future of App Development9 series
 
SwiftUI - Performance and Memory Management
SwiftUI - Performance and Memory ManagementSwiftUI - Performance and Memory Management
SwiftUI - Performance and Memory ManagementWannitaTolaema
 
Oracle Forms Creation
Oracle Forms CreationOracle Forms Creation
Oracle Forms CreationSekhar Byna
 
What is flutter and why should i care?
What is flutter and why should i care?What is flutter and why should i care?
What is flutter and why should i care?Sergi Martínez
 
Java Sending mail
Java Sending mailJava Sending mail
Java Sending mailThao Ho
 
Basics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdfBasics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdfKnoldus Inc.
 
Mobile Application Project report
Mobile Application Project reportMobile Application Project report
Mobile Application Project reportChin2uuu
 
Flutter overview - advantages & disadvantages for business
Flutter overview - advantages & disadvantages for businessFlutter overview - advantages & disadvantages for business
Flutter overview - advantages & disadvantages for businessBartosz Kosarzycki
 
Getting started with flutter
Getting started with flutterGetting started with flutter
Getting started with flutterrihannakedy
 

Tendances (20)

Rest API
Rest APIRest API
Rest API
 
Flutter
Flutter Flutter
Flutter
 
Flutter: Future of App Development
Flutter: Future of App DevelopmentFlutter: Future of App Development
Flutter: Future of App Development
 
SwiftUI - Performance and Memory Management
SwiftUI - Performance and Memory ManagementSwiftUI - Performance and Memory Management
SwiftUI - Performance and Memory Management
 
React js
React jsReact js
React js
 
React js
React jsReact js
React js
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
Oracle Forms Creation
Oracle Forms CreationOracle Forms Creation
Oracle Forms Creation
 
Angular
AngularAngular
Angular
 
What is flutter and why should i care?
What is flutter and why should i care?What is flutter and why should i care?
What is flutter and why should i care?
 
REST API Basics
REST API BasicsREST API Basics
REST API Basics
 
Java Sending mail
Java Sending mailJava Sending mail
Java Sending mail
 
Basics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdfBasics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdf
 
Mobile Application Project report
Mobile Application Project reportMobile Application Project report
Mobile Application Project report
 
Flutter overview - advantages & disadvantages for business
Flutter overview - advantages & disadvantages for businessFlutter overview - advantages & disadvantages for business
Flutter overview - advantages & disadvantages for business
 
Angular routing
Angular routingAngular routing
Angular routing
 
Flutter
FlutterFlutter
Flutter
 
Getting started with flutter
Getting started with flutterGetting started with flutter
Getting started with flutter
 
Flutter workshop
Flutter workshopFlutter workshop
Flutter workshop
 
Ajax cheat sheet
Ajax cheat sheetAjax cheat sheet
Ajax cheat sheet
 

Similaire à How to Validate Form With Flutter BLoC.pptx

User Forms & API integration
User Forms & API integrationUser Forms & API integration
User Forms & API integrationKnoldus Inc.
 
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 FinalSunil Patil
 
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 applicationKaty Slemon
 
Managed Extensibility Framework (MEF)
Managed Extensibility Framework (MEF)Managed Extensibility Framework (MEF)
Managed Extensibility Framework (MEF)Mohamed Meligy
 
HTML5 Up and Running
HTML5 Up and RunningHTML5 Up and Running
HTML5 Up and RunningCodemotion
 
Better User Experience with .NET
Better User Experience with .NETBetter User Experience with .NET
Better User Experience with .NETPeter Gfader
 
Subscribed zuora forsalesforce training -section301-final
Subscribed zuora forsalesforce training -section301-finalSubscribed zuora forsalesforce training -section301-final
Subscribed zuora forsalesforce training -section301-finalSamuel Sharaf
 
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.pptxMongoDB
 
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 MongoDBMongoDB
 
Online bus pass registration
Online bus pass registrationOnline bus pass registration
Online bus pass registrationYesu Raj
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010vchircu
 
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 2008Jonas Follesø
 
Login Project with introduction .pptx
Login Project with introduction .pptxLogin Project with introduction .pptx
Login Project with introduction .pptxkulmiyealiabdille
 

Similaire à 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
 

Plus de BOSC Tech Labs

GoRouter_ The Key to Next-Level Routing in Flutter Development.pdf
GoRouter_ The Key to Next-Level Routing in Flutter Development.pdfGoRouter_ The Key to Next-Level Routing in Flutter Development.pdf
GoRouter_ The Key to Next-Level Routing in Flutter Development.pdfBOSC Tech Labs
 
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.pdfBOSC Tech Labs
 
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_.pdfBOSC Tech Labs
 
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.pdfBOSC Tech Labs
 
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.pdfBOSC Tech Labs
 
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_.pdfBOSC Tech Labs
 
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.pdfBOSC Tech Labs
 
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_.pdfBOSC Tech Labs
 
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.pdfBOSC Tech Labs
 
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_.pdfBOSC Tech Labs
 
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.pdfBOSC Tech Labs
 
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_.pdfBOSC Tech Labs
 
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.pdfBOSC Tech Labs
 
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.pdfBOSC Tech Labs
 
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...BOSC Tech Labs
 
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.pdfBOSC Tech Labs
 
React 19: Revolutionizing Web Development
React 19: Revolutionizing Web DevelopmentReact 19: Revolutionizing Web Development
React 19: Revolutionizing Web DevelopmentBOSC Tech Labs
 
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 & BenefitsBOSC Tech Labs
 
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?BOSC Tech Labs
 
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 TrendsBOSC Tech Labs
 

Plus de BOSC Tech Labs (20)

GoRouter_ The Key to Next-Level Routing in Flutter Development.pdf
GoRouter_ The Key to Next-Level Routing in Flutter Development.pdfGoRouter_ The Key to Next-Level Routing in Flutter Development.pdf
GoRouter_ The Key to Next-Level Routing in Flutter Development.pdf
 
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
 

Dernier

Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)Gáspár Nagy
 
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...naitiksharma1124
 
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 2024Andreas Granig
 
Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024Soroosh Khodami
 
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 SCAShane Coughlan
 
How to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabberHow to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabbereGrabber
 
how-to-download-files-safely-from-the-internet.pdf
how-to-download-files-safely-from-the-internet.pdfhow-to-download-files-safely-from-the-internet.pdf
how-to-download-files-safely-from-the-internet.pdfMehmet Akar
 
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...Lisi Hocke
 
Jax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined DeckJax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined DeckMarc Lester
 
Prompt Engineering - an Art, a Science, or your next Job Title?
Prompt Engineering - an Art, a Science, or your next Job Title?Prompt Engineering - an Art, a Science, or your next Job Title?
Prompt Engineering - an Art, a Science, or your next Job Title?Maxim Salnikov
 
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 2024Chirag Panchal
 
Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024Henry Schreiner
 
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 2024MulesoftMunichMeetup
 
Evolving Data Governance for the Real-time Streaming and AI Era
Evolving Data Governance for the Real-time Streaming and AI EraEvolving Data Governance for the Real-time Streaming and AI Era
Evolving Data Governance for the Real-time Streaming and AI Eraconfluent
 
Community is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea GouletCommunity is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea GouletAndrea Goulet
 
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.pdfSrushith Repakula
 
^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto
^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto
^Clinic ^%[+27788225528*Abortion Pills For Sale In sowetokasambamuno
 
^Clinic ^%[+27788225528*Abortion Pills For Sale In birch acres
^Clinic ^%[+27788225528*Abortion Pills For Sale In birch acres^Clinic ^%[+27788225528*Abortion Pills For Sale In birch acres
^Clinic ^%[+27788225528*Abortion Pills For Sale In birch acreskasambamuno
 

Dernier (20)

Abortion Clinic In Springs ](+27832195400*)[ 🏥 Safe Abortion Pills in Springs...
Abortion Clinic In Springs ](+27832195400*)[ 🏥 Safe Abortion Pills in Springs...Abortion Clinic In Springs ](+27832195400*)[ 🏥 Safe Abortion Pills in Springs...
Abortion Clinic In Springs ](+27832195400*)[ 🏥 Safe Abortion Pills in Springs...
 
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
 
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...
 
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
 
Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024
 
Abortion Clinic Pretoria ](+27832195400*)[ Abortion Clinic Near Me ● Abortion...
Abortion Clinic Pretoria ](+27832195400*)[ Abortion Clinic Near Me ● Abortion...Abortion Clinic Pretoria ](+27832195400*)[ Abortion Clinic Near Me ● Abortion...
Abortion Clinic Pretoria ](+27832195400*)[ Abortion Clinic Near Me ● Abortion...
 
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
 
How to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabberHow to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabber
 
how-to-download-files-safely-from-the-internet.pdf
how-to-download-files-safely-from-the-internet.pdfhow-to-download-files-safely-from-the-internet.pdf
how-to-download-files-safely-from-the-internet.pdf
 
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...
 
Jax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined DeckJax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined Deck
 
Prompt Engineering - an Art, a Science, or your next Job Title?
Prompt Engineering - an Art, a Science, or your next Job Title?Prompt Engineering - an Art, a Science, or your next Job Title?
Prompt Engineering - an Art, a Science, or your next Job Title?
 
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
 
Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024
 
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
 
Evolving Data Governance for the Real-time Streaming and AI Era
Evolving Data Governance for the Real-time Streaming and AI EraEvolving Data Governance for the Real-time Streaming and AI Era
Evolving Data Governance for the Real-time Streaming and AI Era
 
Community is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea GouletCommunity is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea Goulet
 
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
 
^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto
^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto
^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto
 
^Clinic ^%[+27788225528*Abortion Pills For Sale In birch acres
^Clinic ^%[+27788225528*Abortion Pills For Sale In birch acres^Clinic ^%[+27788225528*Abortion Pills For Sale In birch acres
^Clinic ^%[+27788225528*Abortion Pills For Sale In birch acres
 

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/