How to make wrap content for ListView - flutter

I need to make dialog with form input fields and when i use with column content is fit to screen but when i try to type values it hiding the below input fields and submit button.Show to solve this issue i only know one soluction that replacing column with listview and works it allow me to scrool but the content is not fit to screen. How to make the content in listview fit to sceen?
Here is my full code
import 'package:devaayanam/Confi.dart';
import 'package:flutter/material.dart';
class BookPujaDialogContent extends StatefulWidget {
BookPujaDialogContent({Key key}) : super(key: key);
#override
_BookPujaDialogContentState createState() => _BookPujaDialogContentState();
}
class _BookPujaDialogContentState extends State<BookPujaDialogContent> {
final _formKey =GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
return Container(
child: Form(
key: _formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
TextFormField(
decoration: InputDecoration(
labelText: Confi.TEMPLENAME
),
validator: (value) {
if (value.isEmpty) {
return 'Please enter '+Confi.TEMPLENAME;
}
return null;
},
),
TextFormField(
decoration: InputDecoration(
labelText: Confi.DEITY
),
validator: (value) {
if (value.isEmpty) {
return 'Please enter '+Confi.DEITY;
}
return null;
},
),
TextFormField(
decoration: InputDecoration(
labelText: Confi.BN
),
validator: (value) {
if (value.isEmpty) {
return 'Please enter '+Confi.BN;
}
return null;
},
),
TextFormField(
decoration: InputDecoration(
labelText: Confi.STAR
),
validator: (value) {
if (value.isEmpty) {
return 'Please enter '+Confi.STAR;
}
return null;
},
),
Container(
margin: EdgeInsets.only(top: 20),
child: RaisedButton(
onPressed: () {
// Validate returns true if the form is valid, or false
// otherwise.
if (_formKey.currentState.validate()) {
// If the form is valid, display a Snackbar.
Scaffold.of(context)
.showSnackBar(SnackBar(content: Text('Processing Data')));
}
},
textColor: Colors.white,
padding: const EdgeInsets.all(0.0),
shape:RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
child: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: <Color>[
Color(0xFF0D47A1),
Color(0xFF1976D2),
Color(0xFF42A5F5),
],
),
borderRadius: BorderRadius.all(Radius.circular(10.0))
),
width: MediaQuery.of(context).size.width,
height: 40,
// padding: const EdgeInsets.fromLTRB(45, 10, 45, 10),
child: Center(
child: Text(
Confi.BOOKNOW,
style: TextStyle(fontSize: 16)
),
),
),
),
)
],
),
),
);
}
}

Set shirinkWrap: true in ListView.
Dialog(
child: Form(
key: _formKey,
child: ListView(
shrinkWrap: true, //TODO: Use this
children: <Widget>[
TextFormField(
decoration: InputDecoration(labelText: Confi.TEMPLENAME),
validator: (value) {
if (value.isEmpty) {
return 'Please enter ' + Confi.TEMPLENAME;
}
return null;
},
),
....
....

Related

Flutter Simple Login Page

I am a flutter beginner. How to make a simple login page in flutter like this. I tried, but I get a lot of errors. Can anyone help to resolve this?
Please see here to find what I want
Thanks in advance!...............
My code:
Container(
width: 350,
child: TextField(
decoration: InputDecoration(
label Text: 'Email',
),
),
),
Container(
width: 350,
child: TextField(
obscureText: true,
decoration: InputDecoration(
label Text: 'Password',
suffixIcon: Icon(CupertinoIcons.eye_slash_fill,
size: 17),
),
),
),
Padding(
padding: EdgeInserts.fromLTRB(20,20,40,40),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text('Forget Password')
],
),
),
GestureDetector(
child: Container(
alignment: Alignment.center,
width: 250,
child: TextField(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(50),
),
child: Padding(
padding: EdgeInsets.all(top: 12),
child: Text('LOGIN')
),
),
),
),
],
),
),
),
);
}
}
import 'package:flutter/material.dart';
class LoginScreen extends StatefulWidget {
#override
_LoginScreenState createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
final _formKey = GlobalKey<FormState>();
String _email, _password;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Login Screen'),
),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextFormField(
validator: (input) {
if (input.isEmpty) {
return 'Please enter an email';
}
return null;
},
onSaved: (input) => _email = input,
decoration: InputDecoration(
labelText: 'Email',
),
),
TextFormField(
validator: (input) {
if (input.length < 6) {
return 'Your password needs to be at least 6 characters';
}
return null;
},
onSaved: (input) => _password = input,
decoration: InputDecoration(
labelText: 'Password',
),
obscureText: true,
),
RaisedButton(
onPressed: () {
if (_formKey.currentState.validate()) {
_formKey.currentState.save();
// This is where you can handle the login logic
}
},
child: Text('Submit'),
),
],
),
),
),
);
}
}
This is sample code of Login screen.
For get more design and code head to https://flutterawesome.com/tag/login-screen
there is lot of sample code available. And I think you can get better idea from it.

Form validator is not showing error in flutter why?

I created form when i click on button to validate validator not showing error.
GlobalKey<FormState> formkey= GlobalKey<FormState>();
Created Global Key in my code
Form(
key: formkey,
child: ListView(
scrollDirection: Axis.vertical,
children: [
Padding(
padding: const EdgeInsets.all(20),
child: TextFormField(
controller: _name,
validator: (value) {
if (value == null || value == value.isEmpty) {
return "Enter Name";
}
return null;
},
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(),
focusedBorder: OutlineInputBorder(),
labelText: "Name",
prefixIcon: Icon(Icons.person),
errorStyle: TextStyle(color: Colors.red)),
),
),
I created form
Center(
child: ElevatedButton(
onPressed: () {
if (formkey.currentState!.validate()) {
setState(() {
name = _name.text;
email = _email.text;
password = _password.text;
});
addUser();
clear();
}
},
child: Text("Register"))),
Code of button
This is the code help me.
remove value == from the condition it will work.
write like this
if (value == null || value.isEmpty)
I solved your answer like this:
import 'package:flutter/material.dart';
class MyStackAns extends StatefulWidget {
const MyStackAns({super.key});
#override
State<MyStackAns> createState() => _MyStackAnsState();
}
class _MyStackAnsState extends State<MyStackAns> {
GlobalKey<FormState> formkey = GlobalKey<FormState>();
final TextEditingController _name = TextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Stack Answers'),
),
body: Column(
children: [
Form(
key: formkey,
autovalidateMode: AutovalidateMode.onUserInteraction,
child: Padding(
padding: const EdgeInsets.all(20),
child: TextFormField(
controller: _name,
validator: (value) {
if (value == null || value.isEmpty) {
return "Enter Name";
}
return null;
},
decoration: const InputDecoration(
enabledBorder: OutlineInputBorder(), focusedBorder: OutlineInputBorder(), labelText: "Name", prefixIcon: Icon(Icons.person), errorStyle: TextStyle(color: Colors.red)),
),
),
),
Center(
child: ElevatedButton(
onPressed: () {
if (formkey.currentState!.validate()) {
//Perform your validate task here
}
},
child: const Text("Register"))),
],
),
);
}
}

TextFormField Validation Not Working Correctly

I am new to Flutter development, and I'm currently working on the sign in screen for my first full application. I apologize if this has already been asked, but I cannot figure out where my code is going wrong. I'm attempting to test basic form validation, just checking whether anything has been written into the form fields before I continue.
The code for my form is as follows:
class SignInForm extends StatefulWidget {
const SignInForm({super.key});
#override
SignInFormState createState() {
return SignInFormState();
}
}
class SignInFormState extends State<SignInForm> {
final _signInFormKey = GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
return Form(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextFormField(
decoration: const InputDecoration(
border: OutlineInputBorder(),
hintText: 'Username',
),
validator: (String? value) {
if (value == null || value.isEmpty) {
return 'Please enter a valid username';
}
return null;
},
),
Padding(
padding: EdgeInsets.only(top: 20),
child: TextFormField(
obscureText: true,
enableSuggestions: false,
autocorrect: false,
decoration: const InputDecoration(
border: OutlineInputBorder(),
hintText: 'Password',
),
validator: (String? value) {
if (value == null || value.isEmpty) {
return 'Please enter a valid password';
}
return null;
},
),
),
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
TextButton(
style: ButtonStyle(
foregroundColor: MaterialStateProperty.all<Color>(Color(0xFF0b2240)),
),
onPressed: () {
if (_signInFormKey.currentState!.validate()) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Processing Data')),
);
}
},
child: const Text('Log In'),
),
],
),
),
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
TextButton(
style: ButtonStyle(
foregroundColor: MaterialStateProperty.all<Color>(Color(0xFF0b2240)),
),
onPressed: () {
if (_signInFormKey.currentState!.validate()) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Processing Data')),
);
}
},
child: const Text('+ Sign Up'),
),
],
),
),
],
),
);
}
}
Thanks in advance for any help improving my code!
Your forgot the key for the form widget, that's why validation don't work.
#override
Widget build(BuildContext context) {
return Form(
key: _signInFormKey,
child: Column(
...
More infos here : https://docs.flutter.dev/cookbook/forms/validation

How to get form variables in flutter

I have a form in flutter and when you press the button it will call a post function that register a user but i can't acces to the variables in the form.
I want to acces to the username, email and password input values to make a post and register a user
I have divide it in diferents widgets, here the code:
The form
This is the form widget that I have in my register screen
Form(
key: _formKey,
child: SingleChildScrollView(
physics: AlwaysScrollableScrollPhysics(),
padding: EdgeInsets.symmetric(
horizontal: 40.0,
vertical: 60.0,
),
child: Column(
children: <Widget>[
new Container(
child: Image.asset(
'../../assets/logo-feec.png',
width: 200,
),
padding: EdgeInsets.symmetric(vertical: 15),
alignment: Alignment.topCenter,
),
buildUsernameTF(),
SizedBox(
height: 30.0,
),
buildEmailTF(),
SizedBox(
height: 30.0,
),
buildPasswordTF(),
SizedBox(
height: 30.0,
),
buildConfirmPasswordTF(),
Container(
padding: EdgeInsets.symmetric(vertical: 25.0),
width: 200,
child: ElevatedButton.icon(
onPressed: () async {
if (_formKey.currentState.validate()) {
futureString = await resource.MyHttpService().registerUser(username, email, password);
/* Here we want to access the variables */
}
},
label: Text('Envia'),
icon: Icon(Icons.login),
style: ElevatedButton.styleFrom(
primary: Colors.white,
onPrimary: Colors.black,
shape: const BeveledRectangleBorder(
borderRadius:
BorderRadius.all(Radius.circular(3))),
)),
),
Container(
padding: EdgeInsets.all(5),
width: 200,
child: TextButton(
onPressed: () => RouterConfig.router.navigateTo(
context,
"login",
transition: TransitionType.nativeModal,
),
child: Text("Inicia sessió"),
),
)
],
)),
)
The widgets
These are the widgets called in the form
import 'package:flutter/material.dart';
import 'package:email_validator/email_validator.dart';
final TextEditingController _confirmPass = TextEditingController();
final TextEditingController _pass = TextEditingController();
Widget buildPasswordTF() {
return Container(
width: 600,
child: TextFormField(
controller: _pass,
obscureText: true,
decoration: const InputDecoration(
icon: Icon(Icons.lock),
hintText: 'Enter password',
labelText: 'Password *'),
validator: (password) {
if (password == null || password.isEmpty) {
return 'invalid Password';
}
return null;
},
),
);
}
Widget buildConfirmPasswordTF() {
return Container(
width: 600,
child: TextFormField(
controller: _confirmPass,
obscureText: true,
decoration: const InputDecoration(
icon: Icon(Icons.lock),
hintText: 'Enter password',
labelText: 'Password *'),
validator: (password) {
if (password == null || password.isEmpty) {
return 'Invalid Password';
}
if (password != _pass.text) {
return 'Passwords don\'t match';
}
return null;
},
),
);
}
Widget buildUsernameTF() {
return Container(
width: 600,
child: TextFormField(
decoration: const InputDecoration(
icon: Icon(Icons.person),
hintText: 'Enter Username',
labelText: 'Username'),
validator: (username) {
if (username == null || username.isEmpty) {
return 'Invalid Username';
}
return null;
},
),
);
}
Widget buildEmailTF() {
return Container(
width: 600,
child: TextFormField(
decoration: const InputDecoration(
icon: Icon(Icons.mail),
hintText: 'Enter email',
labelText: 'Email *'),
validator: (email) {
if (EmailValidator.validate(email) != true) {
return 'Invalid Email';
}
if (email == null || email.isEmpty) {
return 'Invalid Email';
}
return null;
},
),
);
}
The answer to this will depend on your widget tree but ideally, you would be able to access the TextEditingControllers inside your TextFormFields.
You will need to create TextEditingControllers for each TextFormField:
TextEditingController emailController = TextEditingController();
And then when you submit, you need to access the controller and get the text.
onPressed: () async {
if (_formKey.currentState.validate()) {
futureString = await resource.MyHttpService().registerUser(username, email, password);
/* Here we want to access the variables */
print('Email text: ' + emailController.text);
}
},

How to validate flutter text field for Email or Phone or Null?

How to validate same field for either email or phone or not null??
TextFormField(
// validator: ???,
decoration: InputDecoration(
contentPadding: const EdgeInsets.all(16.0),
hintText: "hint_phone_no_email_address",
filled: true,
fillColor: Colors.grey.withOpacity(0.1),
),
),
I want to validate when I press my button
RaisedButton(
onPressed: () {
// call validate function from here.....
},
textColor: Colors.white,
padding: const EdgeInsets.all(0.0),
child: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: <Color>[
Color(0xFF0D47A1),
Color(0xFF1976D2),
Color(0xFF42A5F5),
],
),
),
child:
Text('Next', style: TextStyle(fontSize: 20)),
),
),
Please let me know...
1. Define Validation methods
Here I use email_validator for verifying the emails and a Regular Expression for the phone numbers. You can either also check intl_phone_field for the phone numbers, or libphonenumber (Though, not yet supported for Web or Desktop):
bool isEmail(String input) => EmailValidator.validate(input);
bool isPhone(String input) => RegExp(
r'^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$'
).hasMatch(input);
2. Define your TextFormField
Then, in your TextFormField, define a GlobalKey<FormFieldState> and a validator where you test for both emails and phone numbers:
TextFormField(
key: _key.value,
validator: (value) {
if (!isEmail(value) && !isPhone(value)) {
return 'Please enter a valid email or phone number.';
}
return null;
},
decoration: InputDecoration(
contentPadding: const EdgeInsets.all(16.0),
hintText: "Enter your phone number or email",
filled: true,
fillColor: Colors.grey.withOpacity(0.1),
),
),
3. Validate the TextFormField on button press
When the user press the button, validate the TextFormField and navigate if valid.
ElevatedButton(
onPressed: () {
if (_key.value.currentState.validate()) {
// Navigate to next page
}
},
style: ButtonStyle(
padding: MaterialStateProperty.all(const EdgeInsets.all(0.0)),
foregroundColor: MaterialStateProperty.all(Colors.white),
backgroundColor: MaterialStateProperty.all(Color(0xFF0D47A1))
),
child: Text('Next', style: TextStyle(fontSize: 20)),
),
Full source code
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:email_validator/email_validator.dart';
void main() {
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
home: HomePage(),
),
);
}
bool isEmail(String input) => EmailValidator.validate(input);
bool isPhone(String input) =>
RegExp(r'^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$')
.hasMatch(input);
class HomePage extends HookWidget {
#override
Widget build(BuildContext context) {
final _key = useState(GlobalKey<FormFieldState>());
return Scaffold(
body: Container(
alignment: Alignment.center,
padding: EdgeInsets.all(16.0),
child: Column(
children: [
TextFormField(
key: _key.value,
validator: (value) {
if (!isEmail(value) && !isPhone(value)) {
return 'Please enter a valid email or phone number.';
}
return null;
},
decoration: InputDecoration(
contentPadding: const EdgeInsets.all(16.0),
hintText: "Enter your phone number or email",
filled: true,
fillColor: Colors.grey.withOpacity(0.1),
),
),
const SizedBox(height: 16.0),
ElevatedButton(
onPressed: () {
if (_key.value.currentState.validate()) {
// Navigate to next page
}
},
style: ButtonStyle(
padding: MaterialStateProperty.all(const EdgeInsets.all(0.0)),
foregroundColor: MaterialStateProperty.all(Colors.white),
backgroundColor:
MaterialStateProperty.all(Color(0xFF0D47A1))),
child: Text('Next', style: TextStyle(fontSize: 20)),
),
],
),
),
);
}
}
Wrap the textFormFields with a Form
Give the Form a key and create this key [_formKey] in initState
Create validator for each TextFormField that needs to be validated when your button is pressed.
Call _formKey.currentState.validate() which returns true if and only if ALL fields are validated otherwise false.
class _SomeClassState extends State<SomeClass>{
GlobalKey<FormState> _formKey; // DECLARE a formKey
#override
void initState(){
super.initState();
_formKey = GlobalKey(); // INSTANTIATE the key here
...
}
/// 4. validate function
void validateController(){
if(!_formKey.currentState.validate()){
// value is false.. textFields are rebuilt in order to show errorLabels
return;
}
// action WHEN values are valid
}
#override
Widget build(BuildContext context){
return Scaffold(
...
// 1. Form should be at the top of the widget tree
Form(
key: _formKey, // 2.
child:
...
TextFormField(
validator:(string) => string.isEmpty // 3. add your validating function here
decoration: InputDecoration(
contentPadding: const EdgeInsets.all(16.0),
hintText: "hint_phone_no_email_address",
filled: true,
fillColor: Colors.grey.withOpacity(0.1),
),
),
...
...
RaisedButton(
onPressed: validateControllers, //4. calls function that validates [when button is pressed ONLY]
textColor: Colors.white,
padding: const EdgeInsets.all(0.0),
child: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: <Color>[
Color(0xFF0D47A1),
Color(0xFF1976D2),
Color(0xFF42A5F5),
],
),
),
child: Text('Next', style: TextStyle(fontSize: 20)),
),
),
...
For section 3, where you plan to create a validator for either 'Email' or 'Phone number', you can use RegExp.
if you want to validate many fields, it is advisable to use the Form widget
first make a form key
final GlobalKey<FormState> formKey = GlobalKey<FormState>();
Form(
key: formKey,
child: Column(
children: <Widget>[
TextFormField(
validator: (String value) {
if (value.isEmpty) {
return 'Email is Required';
}
if (!RegExp(
r"^([a-zA-Z0-9_\-\.]+)#([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$")
.hasMatch(value)) {
return 'Please enter a valid Email';
}
return null;
},
decoration: InputDecoration(
contentPadding: const EdgeInsets.all(16.0),
hintText: "hint_phone_no_email_address",
filled: true,
fillColor: Colors.grey.withOpacity(0.1),
),
),
//validating when the raised button is pressed
RaisedButton(
onPressed: () {
// call validate function from here.....
validateEmail(),
},
textColor: Colors.white,
padding: const EdgeInsets.all(0.0),
child: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: <Color>[
Color(0xFF0D47A1),
Color(0xFF1976D2),
Color(0xFF42A5F5),
],
),
),
child:
Text('Next', style: TextStyle(fontSize: 20)),
),
),
validateEmail()async{
FormState form = formKey.currentState;
form.save();
if (!form.validate()) {
print('Invalid Email');
}else{
print('Credentials are valid');
}
}