How to add extra text boxes in flutter - flutter

https://petercoding.com/firebase/2020/02/25/using-firebase-auth-in-flutter/
Hi all I am new to flutter and following the above guide.
We create four textformfields and each field will contain its own validation. After that we create a Raisedbutton widget that will be the submit button:
How do I actually do this as this only adds 1? Where do I add the others, within this widget. Sorry for noob question
return Form(
key: _formKey,
child: SingleChildScrollView(
child: Column(children: <Widget>[
Padding(
padding: EdgeInsets.all(20.0),
child: TextFormField(
controller: nameController,
decoration: InputDecoration(
labelText: "Enter User Name",
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
// The validator receives the text that the user has entered.
validator: (value) {
if (value.isEmpty) {
return 'Enter User Name';
}
return null;
},
),
),
Thank you in advance

You can copy paste run full code below
You can reference https://flutter.dev/docs/cookbook/forms/validation
code snippet
Padding(
padding: EdgeInsets.all(20.0),
child: TextFormField(
controller: passwordController,
obscureText: true,
decoration: InputDecoration(
labelText: "Enter password",
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
// The validator receives the text that the user has entered.
validator: (value) {
if (value.isEmpty) {
return 'Enter password';
}
return null;
},
),
),
RaisedButton(
onPressed: () {
if (_formKey.currentState.validate()) {}
},
child: Text('Submit'),
)
working demo
full code
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
final _formKey = GlobalKey<FormState>();
TextEditingController emailController = TextEditingController();
TextEditingController nameController = TextEditingController();
TextEditingController passwordController = TextEditingController();
TextEditingController ageController = TextEditingController();
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
void dispose() {
super.dispose();
nameController.dispose();
emailController.dispose();
passwordController.dispose();
ageController.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Form(
key: _formKey,
child: SingleChildScrollView(
child: Column(children: <Widget>[
Padding(
padding: EdgeInsets.all(20.0),
child: TextFormField(
controller: nameController,
decoration: InputDecoration(
labelText: "Enter User Name",
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
// The validator receives the text that the user has entered.
validator: (value) {
if (value.isEmpty) {
return 'Enter User Name';
}
return null;
},
),
),
Padding(
padding: EdgeInsets.all(20.0),
child: TextFormField(
controller: emailController,
decoration: InputDecoration(
labelText: "Enter Email",
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
// The validator receives the text that the user has entered.
validator: (value) {
if (value.isEmpty) {
return 'Enter Email';
}
return null;
},
),
),
Padding(
padding: EdgeInsets.all(20.0),
child: TextFormField(
controller: ageController,
decoration: InputDecoration(
labelText: "Enter age",
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
// The validator receives the text that the user has entered.
validator: (value) {
if (value.isEmpty) {
return 'Enter age';
}
return null;
},
),
),
Padding(
padding: EdgeInsets.all(20.0),
child: TextFormField(
controller: passwordController,
obscureText: true,
decoration: InputDecoration(
labelText: "Enter password",
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
// The validator receives the text that the user has entered.
validator: (value) {
if (value.isEmpty) {
return 'Enter password';
}
return null;
},
),
),
RaisedButton(
onPressed: () {
if (_formKey.currentState.validate()) {}
},
child: Text('Submit'),
)
]))),
);
}
}

Related

Call a function whenever there is a change in Flutter

how can I call a function whenever there is a change in TextFormField .
I have many of them and it's more like an invoice.
So whenever the user changes a value, I need to make some mathematical operations.
The problem is that sometimes some TextFormField could be NULL (User did'tn insert a value yet) and that causes an error.
import 'package:flutter/material.dart';
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
late TextEditingController age = TextEditingController();
late TextEditingController height = TextEditingController();
late TextEditingController weight = TextEditingController();
late TextEditingController result = TextEditingController();
return Scaffold(
appBar: AppBar(
title: const Text('BMI !'),
),
body: Center(
child: DecoratedBox(
decoration: const BoxDecoration(
color: Colors.white10,
),
child: Padding(
padding: const EdgeInsets.all(48.0),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextFormField(
controller:age,
decoration: const InputDecoration(
border: UnderlineInputBorder(),
labelText: 'AGE',
),
),
TextFormField(
controller:height,
decoration: const InputDecoration(
border: UnderlineInputBorder(),
labelText: 'HEIGHT',
),
),
TextFormField(
controller:weight,
decoration: const InputDecoration(
border: UnderlineInputBorder(),
labelText: 'WEIGHT',
),
),
TextFormField(
enabled:false,
controller:result,
decoration: const InputDecoration(
border: UnderlineInputBorder(),
labelText: 'Result',
),
),
],
),
),
),
),
);
}
}
void main() {
runApp(
MaterialApp(
home: MyApp(),
),
);
}
To call a function every time the TextFormField has a change, there's a property for exactly that!
the onChanged property, which fires every time something is typed:
return TextFormField(
onChanged: (value) {
// do something with `value`
},);
Since this is only called once there's a change, you don't have to worry about null
Edit: you can check if the controler.isNotEmpty and do something based on that:
void onChanged(String value){
if (_controller.text.isNotEmpty && _secondController.text.isNotEmpty) {
// do something
} else {
// do something
}
}
return TextFormField(
controller: _controller,
onChanged: (value) => onChanged(value),);

How to set Background image properly in to my code

I want to set background image in to my code but I got this error "Another exception was thrown: Unable to load asset: assets/Onepiece-1.jpg" this one is the error actually it is not an error but the image doesn't appear in the background. I already set my image to in pubspec.yml.I just don't know how to set properly in my code and i dont know what the problem is can some one help my how to fix this error.
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Registration Form',
theme: ThemeData(
primarySwatch: Colors.teal,
),
home: const MyHomePage(title: 'Registration'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
TextEditingController nameController = TextEditingController();
TextEditingController nameController2 = TextEditingController();
TextEditingController nameController3 = TextEditingController();
bool showPassword = false;
TextEditingController nameController4 = TextEditingController();
TextEditingController nameController5 = TextEditingController();
TextEditingController nameController6 = TextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
floatingActionButton: FloatingActionButton.extended(
onPressed: () {},
label: Text('Register'),
icon: const Icon(Icons.upload_file_sharp),
),
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/Onepiece-1.jpg"),
fit: BoxFit.cover,
),
),
child: Column(
children: <Widget>[
Container(
margin: EdgeInsets.all(15),
child: TextField(
controller: nameController,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Username',
),
onChanged: (Text) {
setState(() {});
},
)),
Container(
margin: EdgeInsets.all(15),
child: TextField(
controller: nameController2,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Email Address',
),
onChanged: (Text) {
setState(() {});
},
)),
Container(
margin: EdgeInsets.all(15),
child: TextField(
controller: nameController3,
obscureText: showPassword,
obscuringCharacter: "*",
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Password',
),
onChanged: (Text) {
setState(() {});
},
)),
Container(
margin: EdgeInsets.all(15),
child: TextField(
controller: nameController4,
obscureText: showPassword,
obscuringCharacter: "*",
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Confirm Password',
),
onChanged: (Text) {
setState(() {});
},
)),
TextButton(
onPressed: () {
setState(() {
showPassword = !showPassword;
});
},
child: Text('Show / Hide Password')
),
Container(
margin: EdgeInsets.all(15),
child: TextField(
controller: nameController5,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Address',
),
onChanged: (Text) {
setState(() {});
},
)),
Container(
margin: EdgeInsets.all(15),
child: TextField(
controller: nameController6,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Phone Number',
),
onChanged: (Text) {
setState(() {});
},
)),
])));
}
}
assets Directory
pubspec.yaml
assets:
- assets/images/
source code
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Registration Form',
theme: ThemeData(
primarySwatch: Colors.teal,
),
home: const MyHomePage(title: 'Registration'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
TextEditingController nameController = TextEditingController();
TextEditingController nameController2 = TextEditingController();
TextEditingController nameController3 = TextEditingController();
bool showPassword = false;
TextEditingController nameController4 = TextEditingController();
TextEditingController nameController5 = TextEditingController();
TextEditingController nameController6 = TextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
floatingActionButton: FloatingActionButton.extended(
onPressed: () {},
label: Text('Register'),
icon: const Icon(Icons.upload_file_sharp),
),
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/1-1.JPG"),
fit: BoxFit.cover,
),
),
child: Column(
children: <Widget>[
Container(
margin: EdgeInsets.all(15),
child: TextField(
controller: nameController,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Username',
),
onChanged: (Text) {
setState(() {});
},
)),
Container(
margin: EdgeInsets.all(15),
child: TextField(
controller: nameController2,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Email Address',
),
onChanged: (Text) {
setState(() {});
},
)),
Container(
margin: EdgeInsets.all(15),
child: TextField(
controller: nameController3,
obscureText: showPassword,
obscuringCharacter: "*",
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Password',
),
onChanged: (Text) {
setState(() {});
},
)),
Container(
margin: EdgeInsets.all(15),
child: TextField(
controller: nameController4,
obscureText: showPassword,
obscuringCharacter: "*",
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Confirm Password',
),
onChanged: (Text) {
setState(() {});
},
)),
TextButton(
onPressed: () {
setState(() {
showPassword = !showPassword;
});
},
child: Text('Show / Hide Password')
),
Container(
margin: EdgeInsets.all(15),
child: TextField(
controller: nameController5,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Address',
),
onChanged: (Text) {
setState(() {});
},
)),
Container(
margin: EdgeInsets.all(15),
child: TextField(
controller: nameController6,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Phone Number',
),
onChanged: (Text) {
setState(() {});
},
)),
])));
}
}

Flutter - Text forms not moving above the keyboard upon opening

I am fairly new to flutter and dart as a whole and i have been creating an application that interacts with firebase, this is the code for my registration screen. When clicking on a text input field the keyboard ends up blocking the forms and you cannot see what you are entering... I have tried many things such as singlechildscroll view and resizeToAvoidBottomInset and nothing seems to be affecting it. Anyone have any idea?
Register page:
class RegistrationPage extends StatefulWidget{
const RegistrationPage({Key? key}) : super(key: key);
#override
_RegistrationPageState createState() => _RegistrationPageState();
}
class _RegistrationPageState extends State<RegistrationPage> {
final _auth = FirebaseAuth.instance;
//our form key
final _formKey = GlobalKey<FormState>();
//editing controllers
final firstNameEditingController = new TextEditingController();
final lastNameEditingController = new TextEditingController();
final emailEditingController = new TextEditingController();
final passwordEditingController = new TextEditingController();
final confirmPasswordEditingController = new TextEditingController();
final cityEditingController = new TextEditingController();
#override
Widget build(BuildContext context) {
//firstname Field
final firstNameField = TextFormField(
autofocus: false,
controller: firstNameEditingController,
keyboardType: TextInputType.name,
validator: (value)
{
RegExp regEx = new RegExp(r'^.{2,}$');
if(value!.isEmpty)
{
return("First Name cannot be empty");
}
if(!regEx.hasMatch(value))
{
return("Enter valid name(min 2 characters)");
}
return null;
},
onSaved: (value) {
firstNameEditingController.text = value!;
},
textInputAction: TextInputAction.next,
decoration: InputDecoration(
prefixIcon: Icon(Icons.face),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
hintText: "First name",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
)
));
//Last name Field
final lastNameField = TextFormField(
autofocus: false,
controller: lastNameEditingController,
keyboardType: TextInputType.name,
validator: (value)
{
RegExp regEx = new RegExp(r'^.{2,}$');
if(value!.isEmpty)
{
return("Last Name cannot be empty");
}
return null;
},
onSaved: (value) {
lastNameEditingController.text = value!;
},
textInputAction: TextInputAction.next,
decoration: InputDecoration(
prefixIcon: Icon(Icons.face),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
hintText: "Last name",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
)
));
//email Field
final emailField = TextFormField(
autofocus: false,
controller: emailEditingController,
keyboardType: TextInputType.text,
validator: (value)
{
if(value!.isEmpty)
{
return("Please enter your email");
}
//email validation
if(!RegExp("^[a-zA-Z0-9+_.-]+#[a-zA-Z0-9.-]+.[a-z]").hasMatch(value))
{
return("Please enter a valid email");
}
},
onSaved: (value) {
emailEditingController.text = value!;
},
textInputAction: TextInputAction.next,
decoration: InputDecoration(
prefixIcon: Icon(Icons.account_circle),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
hintText: "Email address",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
)
));
//City
final cityField = TextFormField(
autofocus: false,
controller: cityEditingController,
keyboardType: TextInputType.text,
validator: (value)
{
RegExp regEx = new RegExp(r'^.{2,}$');
if(value!.isEmpty)
{
return("City cannot be empty");
}
return null;
},
onSaved: (value) {
cityEditingController.text = value!;
},
textInputAction: TextInputAction.next,
decoration: InputDecoration(
prefixIcon: Icon(Icons.location_on),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
hintText: "City",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
)
));
//password Field
final passwordField = TextFormField(
autofocus: false,
controller: passwordEditingController,
obscureText: true,
validator: (value)
{
RegExp regEx = new RegExp(r'^.{6,}$');
if(value!.isEmpty)
{
return("Password is required!");
}
if(!regEx.hasMatch(value))
{
return("Enter valid password(Min. 6 characters)");
}
},
onSaved: (value) {
passwordEditingController.text = value!;
},
textInputAction: TextInputAction.next,
decoration: InputDecoration(
prefixIcon: Icon(Icons.lock),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
hintText: "Password",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
)
)
);
//Confirm password Field
final confirmPasswordField = TextFormField(
autofocus: false,
controller: confirmPasswordEditingController,
obscureText: true,
validator: (value)
{
if (confirmPasswordEditingController.text != passwordEditingController.text){
return "Passwords do not match";
}
return null;
},
onSaved: (value) {
confirmPasswordEditingController.text = value!;
},
textInputAction: TextInputAction.done,
decoration: InputDecoration(
prefixIcon: Icon(Icons.lock),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
hintText: "Confirm Password",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
)
)
);
final registerButton = Material(
elevation: 5,
borderRadius: BorderRadius.circular(30),
color: Colors.pink,
child: MaterialButton(
padding: EdgeInsets.fromLTRB(20, 15, 20, 15),
minWidth: MediaQuery.of(context).size.width,
onPressed: () {
signUp(emailEditingController.text, passwordEditingController.text);
},
child: Text("Register", textAlign:TextAlign.center,
style: TextStyle(
fontSize: 20, color: Colors.white, fontWeight: FontWeight.bold),
),
)
);
return Scaffold(
resizeToAvoidBottomInset: false,
backgroundColor: Colors.white,
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
leading: IconButton(
icon: Icon(Icons.arrow_back, color: Colors.pink),
onPressed:(){
Navigator.of(context).pop();
},
)
),
body: Center(
child: new SingleChildScrollView(
reverse: true,
child: Container(
color: Colors.white,
child: Padding(
padding: const EdgeInsets.all(36.0),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
SizedBox(
height: 180,
child: Image.asset(
"assets/logo.png",
fit: BoxFit.contain,
)),
SizedBox(height: 30),
firstNameField,
SizedBox(height: 10),
lastNameField,
SizedBox(height: 10),
emailField,
SizedBox(height:10),
cityField,
SizedBox(height: 10),
passwordField,
SizedBox(height: 10),
confirmPasswordField,
SizedBox(height: 10),
registerButton,
],
),
),
)
)
)
)
);
Main.dart
Future<void> main() async { //asynchronous programming, waits for events to happen before producing a result
WidgetsFlutterBinding.ensureInitialized(); //in this case initializes the Firebase waits for a callback
await Firebase.initializeApp();
runApp(const MyApp());
}
class MyApp extends StatelessWidget { //Used to build application
const MyApp({Key? key}) : super(key: key); //Anything in here runs when the app starts
ThemeData _appTheme() { //The login screen is first to load but this is not in place of main as it is bad practise
final ThemeData base = ThemeData.light(); //Will be used for implementation of light and dark theme
return base.copyWith(
colorScheme: base.colorScheme.copyWith(
primary: travelBlue,
onPrimary: Colors.white,
secondary: travelBlue,
error: travelErrorRed,
),
);
}
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp( //Runs when main.dart is executed
title: 'Login',
theme: _appTheme(),
home: LoginPage(),
);
}
}
try wrapping your column with padding
Padding(
padding: MediaQuery.of(context).viewInsets,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
// your entire form widgets here
]
)
)

How require in a textformfield that the string has uppercase, lowercase and numbers and validate it?

I'm benninger in flutter and I need in my TextFormField a filter, if don't have at least one uppercase or lowercase letter, or a number, show error in a text in red with: "Should be have a number", for example.
This is my form (a part, with the relevant parts: textformfields and the voidinitState()):
class _RegisterState extends State<Register> {
bool showError = false;
bool isButtonActive = true;
String message = '';
String messagcell = '';
#override
void initState() {
super.initState();
correo.addListener(() {
final isButtonActive = correo.text.isNotEmpty;
setState(() => this.isButtonActive = isButtonActive);
});
celular.addListener(() {
final isButtonActive = correo.text.isNotEmpty;
setState(() => this.isButtonActive = isButtonActive);
});
passwd2.addListener(() {
setState(() {
showError = passwd2.text.isEmpty
? false
: passwd.text.trim() != passwd2.text.trim() ||
passwd2.text.length < 8;
});
final isButtonActive = correo.text.isNotEmpty;
setState(() => this.isButtonActive = isButtonActive);
});
passwd.addListener(() {
setState(() {
showError = passwd.text.isEmpty
? false
: passwd.text.trim() != passwd2.text.trim() ||
passwd.text.length < 8;
});
final isButtonActive = correo.text.isNotEmpty;
setState(() => this.isButtonActive = isButtonActive);
});
}
void validateEmail(String enteredEmail) {
if (EmailValidator.validate(enteredEmail)) {
setState(() {
message = '';
});
} else {
setState(() {
message = ('Por favor ingrese un correo válido');
});
}
}
void validateCell(String enteredCell) {
if (enteredCell.length >= 9 && enteredCell.length <= 15) {
setState(() {
messagcell = '';
});
} else if (enteredCell.length < 9) {
setState(() {
messagcell = ('Por favor ingrese un número válido');
});
}
}
TextEditingController correo = TextEditingController();
TextEditingController celular = TextEditingController();
TextEditingController passwd = TextEditingController();
TextEditingController passwd2 = TextEditingController();
#override
void dispose() {
correo.dispose();
passwd.dispose();
celular.dispose();
passwd2.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
height: 900,
child: Card(
color: Colors.blue[200],
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'Register',
style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.allow(
RegExp("[-#._0-9a-zA-Z]")),
new LengthLimitingTextInputFormatter(36),
],
decoration: InputDecoration(
labelText: 'Correo',
prefixIcon: Icon(Icons.mail),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: BorderSide(color: Colors.blue, width: 2.0),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide:
BorderSide(color: Colors.blue[900], width: 2.0),
)),
onChanged: (enteredEmail) => validateEmail(enteredEmail),
controller: correo,
),
),
Text(
message,
style: TextStyle(color: Colors.red),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
// maxLength: 12,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly,
new LengthLimitingTextInputFormatter(15),
],
keyboardType: TextInputType.number,
validator: (value) {
final intNumber = int.tryParse(value);
if (intNumber != null && intNumber <= 9) {
return null;
}
return 'Ingrese un número válido';
},
decoration: InputDecoration(
labelText: 'Celular',
prefixIcon: Icon(Icons.person),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: BorderSide(color: Colors.blue, width: 2.0),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide:
BorderSide(color: Colors.blue[900], width: 2.0),
),
),
onChanged: (enteredCell) => validateCell(enteredCell),
controller: celular,
textInputAction: TextInputAction.done,
),
),
Text(
messagcell,
style: TextStyle(color: Colors.red),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
obscureText: true,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.allow(RegExp("[-0-9a-zA-Z]")),
new LengthLimitingTextInputFormatter(16),
],
decoration: InputDecoration(
labelText: 'Contraseña',
prefixIcon: Icon(Icons.lock),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: BorderSide(color: Colors.blue, width: 2.0),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide:
BorderSide(color: Colors.blue[900], width: 2.0),
),
),
controller: passwd,
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
obscureText: true,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.allow(RegExp("[-0-9a-zA-Z]")),
new LengthLimitingTextInputFormatter(16),
],
decoration: InputDecoration(
labelText: 'Repita contraseña',
prefixIcon: Icon(Icons.lock),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: BorderSide(color: Colors.blue, width: 2.0),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide:
BorderSide(color: Colors.blue[900], width: 2.0),
),
),
controller: passwd2,
),
),
if (showError)
const Text(
"Las contraseñas no son válidas",
style: TextStyle(color: Colors.red),
),
Row(
children: <Widget>[
Expanded(
child: ElevatedButton(
style: ElevatedButton.styleFrom(
onSurface: Colors.blue,
),
child: Text('Register',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.white)),
onPressed: () => [
if (isButtonActive)
{
setState(() => isButtonActive = false),
}
else
{null},
register(), //REGISTER FUNCTION
setState(() {})
],
),
),
//LOGIN BUTTON
Expanded(
child: ElevatedButton(
// color: Colors.amber[100],
child: Text('Login',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.black)),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => MyHomePage(),
),
);
},
),
),
],
)
],
),
),
),
);
}
}
In my TextFormFields have inputFormatters, for example:
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.allow(
RegExp("[-#._0-9a-zA-Z]")),
new LengthLimitingTextInputFormatter(36),
],
I need a function for detect in realtime the absence of any letter in uppercase, lowercase or numeric character. I don't know how make it. Please help me, thanks.
You can use the validator parameter on TextFormField. Your TextFormField will need to be inside a Form widget for this to work. Pass a key to your Form widget and call formKey.currentState?.validate() in the onChanged callback of your TextFormField.
Try out this code below:
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.light(),
home: const Scaffold(
body: Center(
child: CustomForm(),
),
),
);
}
}
class CustomForm extends StatefulWidget {
const CustomForm({Key? key}) : super(key: key);
#override
_CustomFormState createState() => _CustomFormState();
}
class _CustomFormState extends State<CustomForm> {
final formKey = GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
return Form(
key: formKey,
child: Padding(
padding: const EdgeInsets.all(50),
child: TextFormField(
onChanged: (v) => formKey.currentState?.validate(),
validator: (v) {
String? message;
if (!RegExp(".*[0-9].*").hasMatch(v ?? '')) {
message ??= '';
message += 'Input should contain a numeric value 1-9. ';
}
if (!RegExp('.*[a-z].*').hasMatch(v ?? '')) {
message ??= '';
message += 'Input should contain a lowercase letter a-z. ';
}
if (!RegExp('.*[A-Z].*').hasMatch(v ?? '')) {
message ??= '';
message += 'Input should contain an uppercase letter A-Z. ';
}
return message;
},
),
),
);
}
}
Edit: You can also use a key directly on the TextFormField, if you want to only validate that particular field.
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.light(),
home: const Scaffold(
body: Center(
child: CustomForm(),
),
),
);
}
}
class CustomForm extends StatefulWidget {
const CustomForm({Key? key}) : super(key: key);
#override
_CustomFormState createState() => _CustomFormState();
}
class _CustomFormState extends State<CustomForm> {
final formKey = GlobalKey<FormState>();
final passwordFieldKey = GlobalKey<FormFieldState>();
#override
Widget build(BuildContext context) {
return Form(
key: formKey,
child: Padding(
padding: const EdgeInsets.all(50),
child: TextFormField(
key: passwordFieldKey,
onChanged: (v) => passwordFieldKey.currentState?.validate(),
validator: (v) {
String? message;
if (!RegExp(".*[0-9].*").hasMatch(v ?? '')) {
message ??= '';
message += 'Input should contain a numeric value 1-9. ';
}
if (!RegExp('.*[a-z].*').hasMatch(v ?? '')) {
message ??= '';
message += 'Input should contain a lowercase letter a-z. ';
}
if (!RegExp('.*[A-Z].*').hasMatch(v ?? '')) {
message ??= '';
message += 'Input should contain an uppercase letter A-Z. ';
}
return message;
},
),
),
);
}
}

I created a login page and I need to add these things to my username. how i validate my form in flutter

Minimum 1 alphabetic
Minimum 1 number
Allow only Character (_)
its failed
Pattern pattern = r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[_]).{8,}$';
RegExp regex = new RegExp(pattern);
Just check out this example that i have created :
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
TextEditingController userName = TextEditingController();
FocusNode usernameFocus = new FocusNode();
String errorText;
bool _isValid = false;
#override
void initState() {
super.initState();
userName.addListener(() {
String pattern = r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[_]).{8,}$';
RegExp regExp = new RegExp(pattern);
if (userName.text.isEmpty) {
setState(() {
errorText = 'Field cannot be empty';
});
} else {
if (!regExp.hasMatch(userName.text)) {
print('The does not matches the requirement');
setState(() {
// here you can add you text
errorText =
'Minimum 1 Capital letter, 1 small letter and 1 number and _';
_isValid = false;
});
} else {
print('the value matches');
setState(() {
errorText = null;
_isValid = true;
});
}
}
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(left: 20, right: 20),
child: TextField(
focusNode: usernameFocus,
decoration: new InputDecoration(
errorText: errorText,
prefixIcon: Icon(
Icons.supervised_user_circle,
color: Color(0xFF282858),
),
labelText: "UserName",
labelStyle: TextStyle(
fontFamily: "Poppins-Medium",
color: usernameFocus.hasFocus
? Colors.grey[600]
: Colors.grey[600]),
fillColor: Colors.white,
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.grey[400], width: 2.0),
borderRadius: BorderRadius.circular(10.0),
),
border: new OutlineInputBorder(
borderRadius: new BorderRadius.circular(10.0),
borderSide:
new BorderSide(color: Colors.grey[400], width: 2.0),
),
//fillColor: Colors.green
),
controller: userName,
keyboardType: TextInputType.text,
),
),
RaisedButton(
child: Text('Login'),
onPressed: () {
print(_isValid);
if (!_isValid) {
return;
}
print('validation sucess');
},
)
],
)),
),
);
}
}
let me know if it works.
You would need to use a validator on your Textfield. You would add a condtion in the validator function to check if it's false and returns the error meessage that you would like the user to see.
You can either validate by using autovalidate: true, or you can do it manualy by using .currentState.validate() on your form before saving.
so your code could look something like this
validator: (value) {
final alphanumeric = RegExp(YOUR_REGEX_HERE);
if (!alphanumeric.hasMatch(value)) return 'YOUR_ERROR_MESSAGE';
}
You can use this library
pubspec.yaml
flutter_form_builder: ^3.7.3
Code will be like this:
GlobalKey _addextKey = GlobalKey();
FormBuilder(
key: _addextKey,
child: ListView(
children: <Widget>[
TextFormField(
textInputAction: TextInputAction.next,
style: textStyle,
controller: _NameauthController,
// ignore: missing_return
validator: FormBuilderValidators.required(),
decoration: InputDecoration(
hintText: 'name',
hintStyle: TextStyle(fontSize: 12.0),
labelStyle: textStyle,
errorStyle:
TextStyle(color: Colors.red, fontSize: 12.0),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.0))),
keyboardType: TextInputType.text,
),
]);),