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

Flutter technology Based on Web Development
Flutter technology Based on Web Development Flutter technology Based on Web Development
Flutter technology Based on Web Development divyawani2
 
Hybrid application development
Hybrid application developmentHybrid application development
Hybrid application developmentKnoldus Inc.
 
Pune Flutter Presents - Flutter 101
Pune Flutter Presents - Flutter 101Pune Flutter Presents - Flutter 101
Pune Flutter Presents - Flutter 101Arif Amirani
 
Email authentication using firebase auth + flutter
Email authentication using firebase auth + flutterEmail authentication using firebase auth + flutter
Email authentication using firebase auth + flutterKaty Slemon
 
Flutter session 01
Flutter session 01Flutter session 01
Flutter session 01DSC IEM
 
Flutter tutorial for Beginner Step by Step
Flutter tutorial for Beginner Step by StepFlutter tutorial for Beginner Step by Step
Flutter tutorial for Beginner Step by StepChandramouli Biyyala
 
DSC IIITL Flutter Workshop
DSC IIITL Flutter WorkshopDSC IIITL Flutter Workshop
DSC IIITL Flutter WorkshopDSCIIITLucknow
 
Build beautiful native apps in record time with flutter
Build beautiful native apps in record time with flutterBuild beautiful native apps in record time with flutter
Build beautiful native apps in record time with flutterRobertLe30
 
How to Convert a Component Design into an MUI React Code
How to Convert a Component Design into an MUI React CodeHow to Convert a Component Design into an MUI React Code
How to Convert a Component Design into an MUI React CodeWrapPixel
 
Everything about flutter web development
Everything about flutter web developmentEverything about flutter web development
Everything about flutter web developmentKaty Slemon
 
Flutter talkshow
Flutter talkshowFlutter talkshow
Flutter talkshowNhan Cao
 
Google Firebase Presentation
Google Firebase PresentationGoogle Firebase Presentation
Google Firebase PresentationAeni Patel
 

What's hot (20)

Flutter technology Based on Web Development
Flutter technology Based on Web Development Flutter technology Based on Web Development
Flutter technology Based on Web Development
 
Dart programming language
Dart programming languageDart programming language
Dart programming language
 
Hybrid application development
Hybrid application developmentHybrid application development
Hybrid application development
 
React Native
React NativeReact Native
React Native
 
Pune Flutter Presents - Flutter 101
Pune Flutter Presents - Flutter 101Pune Flutter Presents - Flutter 101
Pune Flutter Presents - Flutter 101
 
React Native
React NativeReact Native
React Native
 
Flutter
Flutter Flutter
Flutter
 
Email authentication using firebase auth + flutter
Email authentication using firebase auth + flutterEmail authentication using firebase auth + flutter
Email authentication using firebase auth + flutter
 
Firebase
FirebaseFirebase
Firebase
 
Flutter session 01
Flutter session 01Flutter session 01
Flutter session 01
 
Flutter tutorial for Beginner Step by Step
Flutter tutorial for Beginner Step by StepFlutter tutorial for Beginner Step by Step
Flutter tutorial for Beginner Step by Step
 
DSC IIITL Flutter Workshop
DSC IIITL Flutter WorkshopDSC IIITL Flutter Workshop
DSC IIITL Flutter Workshop
 
React JS
React JSReact JS
React JS
 
Build beautiful native apps in record time with flutter
Build beautiful native apps in record time with flutterBuild beautiful native apps in record time with flutter
Build beautiful native apps in record time with flutter
 
How to Convert a Component Design into an MUI React Code
How to Convert a Component Design into an MUI React CodeHow to Convert a Component Design into an MUI React Code
How to Convert a Component Design into an MUI React Code
 
Everything about flutter web development
Everything about flutter web developmentEverything about flutter web development
Everything about flutter web development
 
Flutter
FlutterFlutter
Flutter
 
Flutter talkshow
Flutter talkshowFlutter talkshow
Flutter talkshow
 
Google Firebase Presentation
Google Firebase PresentationGoogle Firebase Presentation
Google Firebase Presentation
 
Dart Programming.pptx
Dart Programming.pptxDart Programming.pptx
Dart Programming.pptx
 

Similar to 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
 

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

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
 
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...BOSC Tech Labs
 
STEP BY STEP GUIDE TO HIRING EXPERIENCED FLUTTER DEVELOPERS
STEP BY STEP GUIDE TO HIRING EXPERIENCED FLUTTER DEVELOPERSSTEP BY STEP GUIDE TO HIRING EXPERIENCED FLUTTER DEVELOPERS
STEP BY STEP GUIDE TO HIRING EXPERIENCED FLUTTER DEVELOPERSBOSC Tech Labs
 
Top 10 Essential Traits to Look For Hire Remote React Developer
Top 10 Essential Traits to Look For Hire Remote React DeveloperTop 10 Essential Traits to Look For Hire Remote React Developer
Top 10 Essential Traits to Look For Hire Remote React DeveloperBOSC Tech Labs
 
Transform Your Mobile App Development with ChatGPT
Transform Your Mobile App Development with ChatGPTTransform Your Mobile App Development with ChatGPT
Transform Your Mobile App Development with ChatGPTBOSC Tech Labs
 

More from BOSC Tech Labs (20)

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...
 
STEP BY STEP GUIDE TO HIRING EXPERIENCED FLUTTER DEVELOPERS
STEP BY STEP GUIDE TO HIRING EXPERIENCED FLUTTER DEVELOPERSSTEP BY STEP GUIDE TO HIRING EXPERIENCED FLUTTER DEVELOPERS
STEP BY STEP GUIDE TO HIRING EXPERIENCED FLUTTER DEVELOPERS
 
Top 10 Essential Traits to Look For Hire Remote React Developer
Top 10 Essential Traits to Look For Hire Remote React DeveloperTop 10 Essential Traits to Look For Hire Remote React Developer
Top 10 Essential Traits to Look For Hire Remote React Developer
 
Transform Your Mobile App Development with ChatGPT
Transform Your Mobile App Development with ChatGPTTransform Your Mobile App Development with ChatGPT
Transform Your Mobile App Development with ChatGPT
 

Recently uploaded

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 

Recently uploaded (20)

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 

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/