How to set Background image properly in to my code - flutter

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(() {});
},
)),
])));
}
}

Related

Flutter / Dart - change Column to Row and display the result Realtime

Flutter / Dart - I have a simple app but am new to programming, so struggling.
Currently, the setup is with all the TextInput boxes in a Column. I would like to change this to having them in a Row. I assumed this would be easy by simply replacing the Word Column with Row on line 44. But it doesn't work and when I try to run it, the "errors_patch.dart" page opens (which I have never seen before) with a highlighted error on line 51 "int assertionStart, int assertionEnd, Object? message);".
How can I simply change from Column to Row?
How can I have the result show in real time rather than needing to click on the "Subtraction" button to get it?
Many thanks in advance.
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
const appTitle = 'Help with a meal....';
return MaterialApp(
debugShowCheckedModeBanner: false,
title: appTitle,
home: Scaffold(
appBar: AppBar(
title: const Text(appTitle),
backgroundColor: Colors.grey,
foregroundColor: Colors.black,
),
body: const AddTwoNumbers(),
),
);
}
}
class AddTwoNumbers extends StatefulWidget {
const AddTwoNumbers({super.key});
#override
// ignore: library_private_types_in_public_api
_AddTwoNumbersState createState() => _AddTwoNumbersState();
}
class _AddTwoNumbersState extends State<AddTwoNumbers> {
TextEditingController num1controller = TextEditingController();
TextEditingController num2controller = TextEditingController();
TextEditingController num3controller = TextEditingController();
TextEditingController num4controller = TextEditingController();
String result = "0";
#override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(10.0),
child: Column(
children: <Widget>[
TextField(
keyboardType: const TextInputType.numberWithOptions(decimal: true),
controller: num1controller,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Target Level',
hintText: 'Enter First Number',
),
),
const SizedBox(
height: 8,
),
TextField(
keyboardType: const TextInputType.numberWithOptions(decimal: true),
controller: num2controller,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Current Level',
hintText: 'Enter Second Number',
),
),
const SizedBox(
height: 8,
),
TextField(
keyboardType: const TextInputType.numberWithOptions(decimal: true),
controller: num3controller,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Current Meal carbs',
hintText: 'Enter Third Number',
),
),
const SizedBox(
height: 8,
),
TextField(
keyboardType: const TextInputType.numberWithOptions(decimal: true),
controller: num4controller,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Current Meal carbs 2',
hintText: 'Enter Fourth Number',
),
),
const SizedBox(
height: 8,
),
Wrap(children: [
ElevatedButton(
style: ElevatedButton.styleFrom(
foregroundColor: Colors.white,
backgroundColor: Colors.purple),
child: const Text("Subtraction"),
onPressed: () {
setState(() {
double sum = double.parse(num1controller.text) -
double.parse(num2controller.text);
result = sum.toStringAsFixed(1);
});
},
),
const SizedBox(
height: 20,
width: 20,
),
]),
Text('Difference between Target Level and Current Level: $result'),
],
),
);
}
}
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
const appTitle = 'Help with a meal....';
return MaterialApp(
debugShowCheckedModeBanner: false,
title: appTitle,
home: Scaffold(
appBar: AppBar(
title: const Text(appTitle),
backgroundColor: Colors.grey,
foregroundColor: Colors.black,
),
body: const AddTwoNumbers(),
),
);
}
}
class AddTwoNumbers extends StatefulWidget {
const AddTwoNumbers({super.key});
#override
// ignore: library_private_types_in_public_api
_AddTwoNumbersState createState() => _AddTwoNumbersState();
}
class _AddTwoNumbersState extends State<AddTwoNumbers> {
TextEditingController num1controller = TextEditingController();
TextEditingController num2controller = TextEditingController();
TextEditingController num3controller = TextEditingController();
TextEditingController num4controller = TextEditingController();
String result = "0";
_calculate() {
if (num1controller.text.isNotEmpty && num2controller.text.isNotEmpty) {
setState(() {
double sum = double.parse(num1controller.text) -
double.parse(num2controller.text);
result = sum.toStringAsFixed(1);
});
}
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Container(
padding: const EdgeInsets.all(10.0),
child: Column(
children: [
Row(
children: <Widget>[
Expanded(
child: TextField(
onChanged: (value) => _calculate(),
keyboardType:
const TextInputType.numberWithOptions(decimal: true),
controller: num1controller,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Target Level',
hintText: 'Enter First Number',
),
),
),
const SizedBox(
width: 8,
),
Expanded(
child: TextField(
onChanged: (value) => _calculate(),
keyboardType:
const TextInputType.numberWithOptions(decimal: true),
controller: num2controller,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Current Level',
hintText: 'Enter Second Number',
),
),
),
const SizedBox(
width: 8,
),
Expanded(
child: TextField(
onChanged: (value) => _calculate(),
keyboardType:
const TextInputType.numberWithOptions(decimal: true),
controller: num3controller,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Current Meal carbs',
hintText: 'Enter Third Number',
),
),
),
const SizedBox(
width: 8,
),
Expanded(
child: TextField(
onChanged: (value) => _calculate(),
keyboardType:
const TextInputType.numberWithOptions(decimal: true),
controller: num4controller,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Current Meal carbs 2',
hintText: 'Enter Fourth Number',
),
),
),
const SizedBox(
width: 8,
),
],
),
Text(
'Difference between Target Level and Current Level: $result'),
],
),
),
),
);
}
}
Since you are switching to Row it doesn't know the width of the TextFields, so you need to wrap them with Expanded or Flexible widgets to make them take the space they need (or you can give them some fixed width if you wish), something like in the solution below. And the answer to the second question is also in the solution, you just call the calculate method on every TextField change.
class AddTwoNumbers extends StatefulWidget {
const AddTwoNumbers({Key? key}) : super(key: key);
#override
// ignore: library_private_types_in_public_api
_AddTwoNumbersState createState() => _AddTwoNumbersState();
}
class _AddTwoNumbersState extends State<AddTwoNumbers> {
TextEditingController num1controller = TextEditingController();
TextEditingController num2controller = TextEditingController();
TextEditingController num3controller = TextEditingController();
TextEditingController num4controller = TextEditingController();
String result = "0";
_calculate() {
setState(() {
double sum =
double.parse(num1controller.text) - double.parse(num2controller.text);
result = sum.toStringAsFixed(1);
});
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Container(
padding: const EdgeInsets.all(10.0),
child: Column(
children: [
Row(
children: <Widget>[
Expanded(
child: TextField(
onChanged: (value) => _calculate(),
keyboardType:
const TextInputType.numberWithOptions(decimal: true),
controller: num1controller,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Target Level',
hintText: 'Enter First Number',
),
),
),
const SizedBox(
width: 8,
),
Expanded(
child: TextField(
onChanged: (value) => _calculate(),
keyboardType:
const TextInputType.numberWithOptions(decimal: true),
controller: num2controller,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Current Level',
hintText: 'Enter Second Number',
),
),
),
const SizedBox(
width: 8,
),
Expanded(
child: TextField(
onChanged: (value) => _calculate(),
keyboardType:
const TextInputType.numberWithOptions(decimal: true),
controller: num3controller,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Current Meal carbs',
hintText: 'Enter Third Number',
),
),
),
const SizedBox(
width: 8,
),
Expanded(
child: TextField(
onChanged: (value) => _calculate(),
keyboardType:
const TextInputType.numberWithOptions(decimal: true),
controller: num4controller,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Current Meal carbs 2',
hintText: 'Enter Fourth Number',
),
),
),
const SizedBox(
width: 8,
),
],
),
Text(
'Difference between Target Level and Current Level: $result'),
],
),
),
),
);
}
}
There are many ways to do what you're trying to achieve. For changing Column to Rows, you can use a container with a column as a child and rows as children in it. You can see the documentation for further assistance.
For your second question, you can use onChanged() callback or you can use TextEditingController to see the realtime changes in your TextField.

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 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;
},
),
),
);
}
}

Flutter- SingleChildScrollview dont scroll on keybord popup [duplicate]

This question already has answers here:
Flutter TextFormField hidden by keyboard
(13 answers)
Closed 2 years ago.
I'm trying to integrate a signup page. On the keyboard popup, it covers the some input fields on the bottom. Already implemented the Singlechildscrollview. It wont adjust while the keyboard popup. Tried using resizeToAvoidBottomPadding and some other solution, bu no luck. Please help thanks in advance for your help
class _EnterUserDetailsWidgetState extends State<EnterUserDetailsWidget> {
#override
Widget build(BuildContext context) {
final String assetName = 'assets/images/app_logo.svg';
final String pageBg = 'assets/images/user_auth_bg.png';
final String app_logo = 'assets/images/fram_collection_logo.png';
final String phoneIcon = 'assets/images/farm.png';
final _nameController = TextEditingController();
final _phoneController = TextEditingController();
final _emailController = TextEditingController();
final _formKey = GlobalKey<FormState>();
final FocusNode _nameFocusNode = FocusNode();
final FocusNode _emailFocusNode = FocusNode();
final FocusNode _phoneNumberNode = FocusNode();
final FocusNode _dummy = FocusNode();
final itemSpacing = 15.0;
return Scaffold(
resizeToAvoidBottomPadding: false,
body: Stack(
children: [
Image(
image: AssetImage(pageBg),
fit: BoxFit.fill,
height: double.infinity,
width: double.infinity,
),
Container(
height: double.maxFinite,
padding: EdgeInsets.all(10),
child: SingleChildScrollView(
physics: AlwaysScrollableScrollPhysics(),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 50, bottom: 50),
child: Image(
height: 170,
filterQuality: FilterQuality.high,
image: AssetImage(app_logo),
fit: BoxFit.fitWidth,
),
),
TextFormField(
autofocus: true,
decoration: inputDecorationFeild(
hintText: "Email",
labelText: "Enter Email",
textFeildIcon: FarmCollection.email)),
TextFormField(
autofocus: true,
decoration: inputDecorationFeild(
hintText: "Email",
labelText: "Enter Email",
textFeildIcon: FarmCollection.email)),
TextFormField(
autofocus: true,
decoration: inputDecorationFeild(
hintText: "Email",
labelText: "Enter Email",
textFeildIcon: FarmCollection.email)),
TextFormField(
autofocus: true,
decoration: inputDecorationFeild(
hintText: "Email",
labelText: "Enter Email",
textFeildIcon: FarmCollection.email)),
TextFormField(
autofocus: true,
decoration: inputDecorationFeild(
hintText: "Email",
labelText: "Enter Email",
textFeildIcon: FarmCollection.email)),
curvedButtonGreen(
buttonText: "Submit",
onClick: () async {
await Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => OTPverificationWidget(),
),
);
},
),
],
),
),
),
],
),
);
}
_fieldFocusChange(BuildContext context, FocusNode nextFocus) {
// currentFocus.unfocus();
FocusScope.of(context).requestFocus(nextFocus);
}
}
I fixed and share you full code.
Because I don't have a asset file and some component, I replaced with Container or changed.
The main change point is 'resizeToAvoidBottomPadding: true' or remove that.
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> {
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
final String assetName = 'assets/images/app_logo.svg';
final String pageBg = 'assets/images/user_auth_bg.png';
final String app_logo = 'assets/images/fram_collection_logo.png';
final String phoneIcon = 'assets/images/farm.png';
final _nameController = TextEditingController();
final _phoneController = TextEditingController();
final _emailController = TextEditingController();
final _formKey = GlobalKey<FormState>();
final FocusNode _nameFocusNode = FocusNode();
final FocusNode _emailFocusNode = FocusNode();
final FocusNode _phoneNumberNode = FocusNode();
final FocusNode _dummy = FocusNode();
final itemSpacing = 15.0;
return Scaffold(
resizeToAvoidBottomPadding: true,
body: Stack(
children: [
Container(height: 200),
Container(
height: double.maxFinite,
padding: EdgeInsets.all(10),
child: SingleChildScrollView(
physics: AlwaysScrollableScrollPhysics(),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 50, bottom: 50),
child: Container(height: 170),
// child: Image(
// height: 170,
// filterQuality: FilterQuality.high,
// image: AssetImage(app_logo),
// fit: BoxFit.fitWidth,
// ),
),
TextFormField(
autofocus: true,
decoration: InputDecoration(
hintText: "Email",
labelText: "Enter Email",
),
),
TextFormField(
autofocus: true,
decoration: InputDecoration(
hintText: "Email",
labelText: "Enter Email",
),
),
TextFormField(
autofocus: true,
decoration: InputDecoration(
hintText: "Email",
labelText: "Enter Email",
),
),
TextFormField(
autofocus: true,
decoration: InputDecoration(
hintText: "Email",
labelText: "Enter Email",
),
),
TextFormField(
autofocus: true,
decoration: InputDecoration(
hintText: "Email",
labelText: "Enter Email",
),
),
// curvedButtonGreen(
// buttonText: "Submit",
// onClick: () async {
// // await Navigator.of(context).push(
// // MaterialPageRoute(
// // builder: (context) => OTPverificationWidget(),
// // ),
// // );
// },
// ),
],
),
),
),
],
),
);
}
_fieldFocusChange(BuildContext context, FocusNode nextFocus) {
// currentFocus.unfocus();
FocusScope.of(context).requestFocus(nextFocus);
}
}

How to add extra text boxes in 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'),
)
]))),
);
}
}