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

Introduction to c programming language
Introduction to c programming languageIntroduction to c programming language
Introduction to c programming languagesanjay joshi
 
Basic syntax : Algorithm,Flow chart
Basic syntax : Algorithm,Flow chartBasic syntax : Algorithm,Flow chart
Basic syntax : Algorithm,Flow chartPrasanna R Kovath
 
introduction to_mfc
 introduction to_mfc introduction to_mfc
introduction to_mfctuttukuttu
 
(중학생도 이해하는) 에니그마의 작동 원리
(중학생도 이해하는) 에니그마의 작동 원리(중학생도 이해하는) 에니그마의 작동 원리
(중학생도 이해하는) 에니그마의 작동 원리raccoony
 
Multithreading in Android
Multithreading in AndroidMultithreading in Android
Multithreading in Androidcoolmirza143
 
C presentation book
C presentation bookC presentation book
C presentation bookkrunal1210
 
Python Collections Tutorial | Edureka
Python Collections Tutorial | EdurekaPython Collections Tutorial | Edureka
Python Collections Tutorial | EdurekaEdureka!
 
C formatted and unformatted input and output constructs
C  formatted and unformatted input and output constructsC  formatted and unformatted input and output constructs
C formatted and unformatted input and output constructsGopikaS12
 
structured programming
structured programmingstructured programming
structured programmingAhmad54321
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocationViji B
 
Exception Handling
Exception HandlingException Handling
Exception HandlingReddhi Basu
 
C programming language
C programming languageC programming language
C programming languageMaha lakshmi
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpprajshreemuthiah
 
1.-Introduction-to-Dart.pdf
1.-Introduction-to-Dart.pdf1.-Introduction-to-Dart.pdf
1.-Introduction-to-Dart.pdfSamySiddhan
 
Java virtual machine
Java virtual machineJava virtual machine
Java virtual machineNikhil Sharma
 

What's hot (20)

Introduction to c programming language
Introduction to c programming languageIntroduction to c programming language
Introduction to c programming language
 
Basic syntax : Algorithm,Flow chart
Basic syntax : Algorithm,Flow chartBasic syntax : Algorithm,Flow chart
Basic syntax : Algorithm,Flow chart
 
Oracle: Cursors
Oracle: CursorsOracle: Cursors
Oracle: Cursors
 
Chapter17 of clean code
Chapter17 of clean codeChapter17 of clean code
Chapter17 of clean code
 
introduction to_mfc
 introduction to_mfc introduction to_mfc
introduction to_mfc
 
OOP and FP
OOP and FPOOP and FP
OOP and FP
 
(중학생도 이해하는) 에니그마의 작동 원리
(중학생도 이해하는) 에니그마의 작동 원리(중학생도 이해하는) 에니그마의 작동 원리
(중학생도 이해하는) 에니그마의 작동 원리
 
Multithreading in Android
Multithreading in AndroidMultithreading in Android
Multithreading in Android
 
C presentation book
C presentation bookC presentation book
C presentation book
 
Control statements
Control statementsControl statements
Control statements
 
Python Collections Tutorial | Edureka
Python Collections Tutorial | EdurekaPython Collections Tutorial | Edureka
Python Collections Tutorial | Edureka
 
C formatted and unformatted input and output constructs
C  formatted and unformatted input and output constructsC  formatted and unformatted input and output constructs
C formatted and unformatted input and output constructs
 
structured programming
structured programmingstructured programming
structured programming
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
C programming language
C programming languageC programming language
C programming language
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpp
 
1.-Introduction-to-Dart.pdf
1.-Introduction-to-Dart.pdf1.-Introduction-to-Dart.pdf
1.-Introduction-to-Dart.pdf
 
Java virtual machine
Java virtual machineJava virtual machine
Java virtual machine
 

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

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
 
Which Is The Best AI Tool For Mobile App Development_.pdf
Which Is The Best AI Tool For Mobile App Development_.pdfWhich Is The Best AI Tool For Mobile App Development_.pdf
Which Is The Best AI Tool For Mobile App Development_.pdfBOSC Tech Labs
 
Revealing Development Efficiency: How AI Powers Innovation in Software Creati...
Revealing Development Efficiency: How AI Powers Innovation in Software Creati...Revealing Development Efficiency: How AI Powers Innovation in Software Creati...
Revealing Development Efficiency: How AI Powers Innovation in Software Creati...BOSC Tech Labs
 

More from BOSC Tech Labs (20)

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
 
Which Is The Best AI Tool For Mobile App Development_.pdf
Which Is The Best AI Tool For Mobile App Development_.pdfWhich Is The Best AI Tool For Mobile App Development_.pdf
Which Is The Best AI Tool For Mobile App Development_.pdf
 
Revealing Development Efficiency: How AI Powers Innovation in Software Creati...
Revealing Development Efficiency: How AI Powers Innovation in Software Creati...Revealing Development Efficiency: How AI Powers Innovation in Software Creati...
Revealing Development Efficiency: How AI Powers Innovation in Software Creati...
 

Recently uploaded

Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
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
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
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.
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
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
 
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
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
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
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 

Recently uploaded (20)

Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
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...
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
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
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
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
 
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)
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
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
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 

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/