How to get form variables in flutter - forms

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

Related

Exception caught by gesture 'then' was called on null

I faced this error when I tried to insert image
"The following NoSuchMethodError was thrown while handling a gesture:
The method 'then' was called on null.
Receiver: null
Tried calling: then(Closure: (dynamic) => Null)"
Below is my code. Hope someone can help me with it. I have no idea how to solve it. Thank you.
// ignore_for_file: import_of_legacy_library_into_null_safe, unrelated_type_equality_checks
import 'dart:io';
import 'package:dparking/model/user_model.dart';
import 'package:dparking/screens/home_screen.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';
class RegistrationScreen extends StatefulWidget {
const RegistrationScreen({Key? key}) : super(key: key);
#override
State<RegistrationScreen> createState() => _RegistrationScreenState();
}
class _RegistrationScreenState extends State<RegistrationScreen> {
final _auth = FirebaseAuth.instance;
// form key
final _formKey = GlobalKey<FormState>();
// editing Controller
final nameEditingController = TextEditingController();
final emailEditingController = TextEditingController();
final passwordEditingController = TextEditingController();
final confirmPasswordEditingController = TextEditingController();
final phoneNumberEditingController = TextEditingController();
XFile? _logo;
final ImagePicker _picker = ImagePicker();
#override
Widget build(BuildContext context) {
// Name field
final nameField = TextFormField(
autofocus: false,
controller: nameEditingController,
keyboardType: TextInputType.emailAddress,
validator: (value) {
RegExp regex = RegExp(r'^.{3,}$');
if(value!.isEmpty){
return ("Name cannot be Empty");
}
if(!regex.hasMatch(value))
{
return ("Enter Valid Name(Min. 3 Character");
}
return null;
},
onSaved: (value)
{
nameEditingController.text = value!;
},
textInputAction: TextInputAction.next,
decoration: InputDecoration(
prefixIcon: const Icon(Icons.account_circle),
contentPadding: const EdgeInsets.fromLTRB(20, 15, 20, 15),
hintText: "Name",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
);
// Email field
final emailField = TextFormField(
autofocus: false,
controller: emailEditingController,
keyboardType: TextInputType.emailAddress,
validator: (value)
{
if(value!.isEmpty)
{
return ("Please Enter Your Email");
}
// reg expression for email validation
if(!RegExp("^[a-zA-Z0-9+_.-]+#[a-zA-Z0-9.-]+.[a-z]").hasMatch(value))
{
return("Please Enter a valid email");
}
return null;
},
onSaved: (value)
{
emailEditingController.text = value!;
},
textInputAction: TextInputAction.next,
decoration: InputDecoration(
prefixIcon: const Icon(Icons.mail),
contentPadding: const EdgeInsets.fromLTRB(20, 15, 20, 15),
hintText: "Email",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
);
// Password field
final passwordField = TextFormField(
autofocus: false,
controller: passwordEditingController,
obscureText: true,
validator: (value) {
RegExp regex = RegExp(r'^.{6,}$');
if(value!.isEmpty){
return ("Password is required for login");
}
if(!regex.hasMatch(value))
{
return ("Enter Valid Password(Min. 6 Character");
}
return null;
},
onSaved: (value)
{
passwordEditingController.text = value!;
},
textInputAction: TextInputAction.next,
decoration: InputDecoration(
prefixIcon: const Icon(Icons.vpn_key),
contentPadding: const 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.length !=
passwordEditingController.text){
return "Password Does Not Match";
}
return null;
},
onSaved: (value)
{
confirmPasswordEditingController.text = value!;
},
textInputAction: TextInputAction.next,
decoration: InputDecoration(
prefixIcon: const Icon(Icons.vpn_key),
contentPadding: const EdgeInsets.fromLTRB(20, 15, 20, 15),
hintText: "Confirm Password",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
);
//signup button
final signupButton = Material(
elevation: 5,
borderRadius: BorderRadius.circular(30),
color: Colors.redAccent,
child: MaterialButton(
padding: const EdgeInsets.fromLTRB(20, 15, 20, 15),
minWidth: MediaQuery.of(context).size.width,
onPressed: () {
signUp(emailEditingController.text, passwordEditingController.text);
},
child: const Text("SignUp", textAlign: TextAlign.center,
style: TextStyle(fontSize: 20, color: Colors.white, fontWeight: FontWeight.bold,),
),
),
);
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
leading: IconButton(
icon: const Icon(Icons.arrow_back, color: Colors.red),
onPressed: (){
Navigator.of(context).pop();
},
),
),
body: Center(
child: SingleChildScrollView(
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: 200,
width: 300,
child: Image.asset("assets/images/DParking.png",
fit: BoxFit.contain,
color: Colors.black,
),
),
nameField,
const SizedBox(height: 30),
emailField,
const SizedBox(height: 30),
passwordField,
const SizedBox(height: 30),
confirmPasswordField,
const SizedBox(height: 30),
InkWell(
onTap: (){
_pickImage().then((value){ //i think the error is here
setState((){
_logo = value;
});
});
},
child: Card(
elevation: 4,
child: _logo==null ? const SizedBox(
height: 100,
width: 250,
child: Center(
child: Text('Insert Identification Card'),
),
):SizedBox(
height: 100,
width: 250,
child: Image.file(File(_logo!.path),)
),
),
),
const SizedBox(height: 30),
signupButton,
const SizedBox(height: 30),
],
),
),
),
),
),
)
);
}
void signUp(String email, String password) async
{
if (_formKey.currentState!.validate()) {
await _auth
.createUserWithEmailAndPassword(email: email, password: password)
.then((value) => {postDetailsToFirestore()})
.catchError((e) {
Fluttertoast.showToast(msg: e!.message);
});
}
}
postDetailsToFirestore() async {
// call firestore
//call user model
//send value
FirebaseFirestore firebaseFirestore = FirebaseFirestore.instance;
User? user = _auth.currentUser;
UserModel userModel = UserModel();
userModel.email = user!.email;
userModel.uid = user.uid;
userModel.name = nameEditingController.text;
await firebaseFirestore
.collection("users")
.doc(user.uid)
.set(userModel.toMap());
Fluttertoast.showToast(msg: "Account created successfully");
Navigator.pushAndRemoveUntil(
(context),
MaterialPageRoute(builder: (context) => const HomeScreen()),
(route) => false);
}
}
_pickImage() {
}

Cannot send data to database after update data

I'm a newbie in using flutter, so this time I want to explain my problem. I created a data update form, when I want to update the data but the data cannot be updated and sent to the database, can friends here help solve my problem? Here is the source code snippet that I made. Thank you all friends. I hope that friends can also understand my question :)
edit_nasabah.dart
class EditNasabah extends StatefulWidget {
Nasabah nasabah;
EditNasabah({this.nasabah});
#override
_EditNasabahState createState() => _EditNasabahState(this.nasabah);
}
class _EditNasabahState extends State<EditNasabah> {
bool _isLoading = false;
final _formKey = GlobalKey<FormState>();
final _scaffoldKey = GlobalKey<ScaffoldState>();
final Nasabah nasabah;
_EditNasabahState(this.nasabah);
bool _secureText = true;
String nama_debitur, alamat, no_telp, no_ktp, no_selular;
showHide() {
setState(() {
_secureText = !_secureText;
});
}
_showMsg(msg) {
final snackBar = SnackBar(
content: Text(msg),
);
_scaffoldKey.currentState.showSnackBar(snackBar);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Edit Data"),
),
body: Padding(
padding: EdgeInsets.all(10),
child: ListView(
children: [
SizedBox(
height: 10,
),
Card(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const ListTile(
leading: Icon(Icons.info, size: 50),
title: Text('Edit Form Debitur'),
subtitle: Text('Silahkan edit sesuai form dibawah ini'),
),
],
),
),
SizedBox(
height: 10,
),
Form(
key: _formKey,
child: Column(
children: [
TextFormField(
keyboardType: TextInputType.text,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Nama Debitur',
),
validator: (nameValue) {
if (nameValue.isEmpty) {
return 'Please enter your full name';
}
nasabah.nama_debitur = nameValue;
return null;
},
initialValue: "${nasabah.nama_debitur}",
),
SizedBox(
height: 10,
),
TextFormField(
keyboardType: TextInputType.text,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Alamat',
),
validator: (alamatValue) {
if (alamatValue.isEmpty) {
return 'Please enter your full name';
}
alamat = alamatValue;
return null;
},
initialValue: "${nasabah.alamat}",
),
SizedBox(
height: 10,
),
TextFormField(
keyboardType: TextInputType.text,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Nomor Telepon',
),
validator: (notlpValue) {
if (notlpValue.isEmpty) {
return 'Please enter your full name';
}
no_telp = notlpValue;
return null;
},
initialValue: "${nasabah.no_telp}",
),
SizedBox(
height: 10,
),
TextFormField(
keyboardType: TextInputType.text,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'NIK',
),
validator: (noktpValue) {
if (noktpValue.isEmpty) {
return 'Please enter your full name';
}
no_ktp = noktpValue;
return null;
},
initialValue: "${nasabah.no_ktp}",
),
SizedBox(
height: 10,
),
TextFormField(
keyboardType: TextInputType.text,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'No Selular',
),
validator: (nosllValue) {
if (nosllValue.isEmpty) {
return 'Please enter your full name';
}
no_selular = nosllValue;
return null;
},
initialValue: "${nasabah.no_selular}",
),
SizedBox(
height: 10,
),
Container(
alignment: Alignment.centerRight,
margin: EdgeInsets.all(10),
child: RaisedButton(
onPressed: () {
if (_formKey.currentState.validate()) {
_update();
}
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(80.0)),
padding: EdgeInsets.all(0.0),
child: Ink(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Color(0xff374ABE), Color(0xff64B6FF)],
begin: Alignment.centerLeft,
end: Alignment.centerRight,
),
borderRadius: BorderRadius.circular(30.0)),
child: Container(
constraints:
BoxConstraints(maxWidth: 100.0, minHeight: 50.0),
alignment: Alignment.center,
child: Text(
_isLoading? 'Proccessing..' : 'Simpan',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white, fontSize: 15),
),
),
),
),
),
],
),
),
],
),
));
}
This is a function to send data to the database
void _update() async {
setState(() {
_isLoading = true;
});
var data = {nasabah.nama_debitur,nasabah.alamat,nasabah.no_telp,nasabah.no_ktp,nasabah.no_selular};
print(data);
var res = await Network().updateData(data, 'mstdebitur');
var body = json.decode(res.body);
if (res.statusCode == 200) {
SharedPreferences localStorage = await SharedPreferences.getInstance();
localStorage.setString('mstdebitur', json.encode(body['mstdebitur']));
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('Berhasil Disimpan'),
duration: Duration(seconds: 2),
));
} else {
if (body['message']['nama_debitur'] != null) {
_showMsg(body['message']['nama_debitur'][0].toString());
} else if (body['message']['alamat'] != null) {
_showMsg(body['message']['alamat'][0].toString());
} else if (body['message']['no_telp'] != null) {
_showMsg(body['message']['no_telp'][0].toString());
}
else if (body['message']['no_ktp'] != null) {
_showMsg(body['message']['no_ktp'][0].toString());
}
else if (body['message']['no_selular'] != null) {
_showMsg(body['message']['no_selular'][0].toString());
}
ScaffoldMessenger.of(context)
.showSnackBar(new SnackBar(content: Text("Gagal")));
}
setState(() {
_isLoading = false;
});
}
}
api.dart
updateData(apiURL, id) async {
var fullUrl = _url + apiURL + '/' + id.toString();
await _getToken();
return await http.put(
fullUrl,
headers: _setHeaders(),
);
}
nasabah_service.dart
static Future<List<Nasabah>> updateUser(id) async {
final response = await Network().updateData(baseUrl, id,);
List<Nasabah> list = parseResponse(response.body);
return list;
}
I hope friends can help me.
use TextEditingController for each TextFormField1
create text controller variable:
final TextEditingController _nama_debiturController = TextEditingController();
final TextEditingController _alamatController = TextEditingController();
final TextEditingController _no_telpController = TextEditingController();
final TextEditingController _no_ktpController = TextEditingController();
final TextEditingController _no_selularController = TextEditingController();
you can init value form textController in initState()
#override
void initState() {
super.initState();
_nama_debiturController.text = "hel;lo";
_alamatController.text = "Hi";
_no_telpController.text = "He";
}
And edit your TextFormField widget code:
remove initialValue: ,
add controller: ,
Example:
TextFormField(
keyboardType: TextInputType.text,
controller: _nama_debiturController,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Nama Debitur',
),
validator: (nameValue) {
if (nameValue!.isEmpty) {
return 'Please enter your full name';
}
nasabah.nama_debitur = nameValue;
return null;
},
),
in your _update()
void _update() async {
var data = {
_nama_debiturController.text,
_alamatController.text,
_no_telpController.text,
_no_ktpController.text,
_no_selularController.text
};
print(data);
}
your Form:
Form(
key: _formKey,
child: Column(
children: [
TextFormField(
keyboardType: TextInputType.text,
controller: _nama_debiturController,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Nama Debitur',
),
validator: (nameValue) {
if (nameValue!.isEmpty) {
return 'Please enter your full name';
}
nasabah.nama_debitur = nameValue;
return null;
},
),
TextFormField(
keyboardType: TextInputType.text,
controller: _alamatController,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Alamat',
),
validator: (alamatValue) {
if (alamatValue!.isEmpty) {
return 'Please enter your full name';
}
alamat = alamatValue;
return null;
},
),
TextFormField(
keyboardType: TextInputType.text,
controller: _no_telpController,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Nomor Telepon',
),
validator: (notlpValue) {
if (notlpValue!.isEmpty) {
return 'Please enter your full name';
}
no_telp = notlpValue;
return null;
},
),
TextFormField(
keyboardType: TextInputType.text,
controller: _no_ktpController,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'NIK',
),
validator: (noktpValue) {
if (noktpValue!.isEmpty) {
return 'Please enter your full name';
}
no_ktp = noktpValue;
return null;
},
),
TextFormField(
keyboardType: TextInputType.text,
controller: _no_selularController,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'No Selular',
),
validator: (nosllValue) {
if (nosllValue!.isEmpty) {
return 'Please enter your full name';
}
no_selular = nosllValue;
return null;
},
),
Container(
alignment: Alignment.centerRight,
margin: EdgeInsets.all(10),
child: RaisedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
_update();
}
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(80.0)),
padding: EdgeInsets.all(0.0),
child: Ink(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Color(0xff374ABE), Color(0xff64B6FF)],
begin: Alignment.centerLeft,
end: Alignment.centerRight,
),
borderRadius: BorderRadius.circular(30.0)),
child: Container(
constraints:
BoxConstraints(maxWidth: 100.0, minHeight: 50.0),
alignment: Alignment.center,
child: Text(
_isLoading? 'Proccessing..' : 'Simpan',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white, fontSize: 15),
),
),
),
),
),
],
),
),
You are missing body of data in put method
updateData(apiURL, id, Map<String, String> data ) async {
var fullUrl = _url + apiURL + '/' + id.toString();
await _getToken();
return await http.put(
fullUrl,
headers: _setHeaders(),
body: jsonEncode(data),
);
}
your data
Map<String, String> data = {
"body1" : _nama_debiturController.text,
"body1": _alamatController.text,
"body1": _no_telpController.text,
"body1" : _no_ktpController.text,
"body1" : _no_selularController.text
};
print(data);
var res = await Network().updateData(data, 'mstdebitur', data);

How can I upload the first name, last name, job and profile picture of the user?

Please Help me
I want to know how to upload the first name, last name, job, date of birth and a picture of the user in Flutter Null Safety
this is my signup
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:newlivenullsaf/pages/login.dart';
class Signup extends StatefulWidget {
#override
State<Signup> createState() => _SignupState();
}
class _SignupState extends State<Signup> {
final _formkey = GlobalKey<FormState>();
var email = '';
var password = '';
var confirmPassword = '';
#override
void dispose() {
emailController.dispose();
passwordController.dispose();
confirmPasswordController.dispose();
super.dispose();
}
bool isLoading = false;
final nameController = TextEditingController();
final emailController = TextEditingController();
final passwordController = TextEditingController();
final confirmPasswordController = TextEditingController();
registeration() async {
if (password == confirmPassword) {
try {
UserCredential userCredential = await FirebaseAuth.instance
.createUserWithEmailAndPassword(email: email, password: password);
print(UserCredential);
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
backgroundColor: Colors.blueGrey,
content: Text(
'Registerd Successfully. Please Sign In ',
style: TextStyle(fontSize: 20.0),
),
),
);
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => const LoginPage(),
),
);
} on FirebaseAuthException catch (error) {
if (error.code == 'week-password') {
print('Password is too week');
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
backgroundColor: Colors.blueGrey,
content: Text(
'Password is too week ',
style: TextStyle(fontSize: 20.0, color: Colors.amberAccent),
),
),
);
} else if (error.code == 'email-already-in-use') {
print('Account is already exists');
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
backgroundColor: Colors.blueGrey,
content: Text(
'Account is already exists ',
style: TextStyle(fontSize: 20.0, color: Colors.amberAccent),
),
),
);
}
}
} else {
print('Password and Confirm Password does not match ');
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
backgroundColor: Colors.blueGrey,
content: Text(
'Password and Confirm Password does not match ',
style: TextStyle(fontSize: 20.0, color: Colors.amberAccent),
),
),
);
}
}
#override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
return Scaffold(
backgroundColor: Colors.white,
body: isLoading
? Center(
child: Container(
height: size.height / 20,
width: size.height / 20,
child: CircularProgressIndicator(),
),
)
: Form(
key: _formkey,
child: Padding(
padding: const EdgeInsets.symmetric(
vertical: 20.0, horizontal: 20.0),
child: ListView(
children: [
Padding(
padding: const EdgeInsets.all(30.0),
child: Image.asset('images/signup.png'),
),
Container(
margin: const EdgeInsets.symmetric(vertical: 10.0),
child: TextFormField(
autofocus: false,
decoration: const InputDecoration(
labelText: 'Name:',
labelStyle: TextStyle(fontSize: 20.0),
border: OutlineInputBorder(),
errorStyle: TextStyle(
color: Colors.black26, fontSize: 15.0),
),
controller: nameController,
validator: (value) {
if (value == null || value.isNotEmpty) {
return 'Please Enter Your Name';
}
if (value.length > 4) {
return (' Name(Max. 4 Character)');
}
return null;
}),
),
Container(
margin: const EdgeInsets.symmetric(vertical: 10.0),
child: TextFormField(
autofocus: false,
decoration: const InputDecoration(
labelText: 'Last Name:',
labelStyle: TextStyle(fontSize: 20.0),
border: OutlineInputBorder(),
errorStyle: TextStyle(
color: Colors.black26, fontSize: 15.0),
),
controller: nameController,
validator: (value) {
if (value == null || value.isNotEmpty) {
return 'Please Enter Your Last Name';
}
if (value.length > 4) {
return ('Last Name(Max. 4 Character)');
}
return null;
}),
),
Container(
margin: const EdgeInsets.symmetric(vertical: 10.0),
child: TextFormField(
autofocus: false,
decoration: const InputDecoration(
labelText: 'Email:',
labelStyle: TextStyle(fontSize: 20.0),
border: OutlineInputBorder(),
errorStyle:
TextStyle(color: Colors.black26, fontSize: 15.0),
),
controller: emailController,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please Enter Email';
} else if (!value.contains('#')) {
return 'Please Enter Valid Email';
}
return null;
},
),
),
Container(
margin: const EdgeInsets.symmetric(vertical: 10.0),
child: TextFormField(
autofocus: false,
obscureText: true,
decoration: const InputDecoration(
labelText: ' Password',
labelStyle: TextStyle(fontSize: 20.0),
border: OutlineInputBorder(),
errorStyle:
TextStyle(color: Colors.black26, fontSize: 15.0),
),
controller: passwordController,
validator: (value) {
if (value == null ||
value.isEmpty ||
value.length < 6 ||
value.length > 14) {
return 'Please Enter Password';
}
return null;
},
),
),
Container(
margin: const EdgeInsets.symmetric(vertical: 10.0),
child: TextFormField(
autofocus: false,
obscureText: true,
decoration: const InputDecoration(
labelText: 'Confirm Password',
labelStyle: TextStyle(fontSize: 20.0),
border: OutlineInputBorder(),
errorStyle:
TextStyle(color: Colors.black26, fontSize: 15.0),
),
controller: confirmPasswordController,
validator: (value) {
if (value == null ||
value.isEmpty ||
value.length < 6 ||
value.length > 14) {
return 'Please Confirm Password';
}
return null;
},
),
),
const SizedBox(
height: 10.0,
),
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
if (_formkey.currentState!.validate()) {
setState(() {
email = emailController.text;
password = passwordController.text;
confirmPassword =
confirmPasswordController.text;
});
registeration();
}
},
child: const Text(
'Signup ',
style: TextStyle(fontSize: 18.0),
),
),
],
),
),
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('Already Have An Account ?'),
TextButton(
onPressed: () {
Navigator.pushReplacement(
context,
PageRouteBuilder(
pageBuilder:
(context, animation1, animation2) =>
const LoginPage(),
transitionDuration:
const Duration(seconds: 0),
),
);
},
child: const Text('Login'),
),
],
),
),
],
),
),
),
);
}
}
this is my main
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:newlivenullsaf/pages/login.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
final Future<FirebaseApp> _initialization = Firebase.initializeApp();
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: _initialization,
builder: (context, snapshot) {
if (snapshot.hasError) {
print('something wrong');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(),
);
}
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter email & password',
theme: ThemeData(primarySwatch: Colors.blue),
home: const LoginPage(),
);
},
);
}
}
this is my login
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:newlivenullsaf/pages/forget_password.dart';
import 'package:newlivenullsaf/pages/signup.dart';
import 'package:newlivenullsaf/pages/user_main.dart';
class LoginPage extends StatefulWidget {
const LoginPage({Key? key}) : super(key: key);
#override
State<LoginPage> createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
final _formKey = GlobalKey<FormState>();
var email = "";
var password = "";
final emailController = TextEditingController();
final passwordController = TextEditingController();
userLogin() async {
try {
await FirebaseAuth.instance
.signInWithEmailAndPassword(email: email, password: password);
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context) => const UserMain()));
} on FirebaseAuthException catch (error) {
if (error.code == ' user-not-found') {
print('No user found for that email ');
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
backgroundColor: Colors.blueGrey,
content: Text(
'No user found for that email',
style: TextStyle(
fontSize: 18.0,
color: Colors.amber,
),
),
),
);
} else if (error.code == 'wrong-password') {
print('wrong password provided by the user');
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
backgroundColor: Colors.blueGrey,
content: Text(
'wrong password provided by the user',
style: TextStyle(
fontSize: 18.0,
color: Colors.amber,
),
),
),
);
}
}
}
#override
void dispose() {
emailController.dispose();
passwordController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Form(
key: _formKey,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 40.0, horizontal: 20.0),
child: ListView(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Image.asset('images/login.jpg'),
),
Container(
margin: const EdgeInsets.symmetric(vertical: 10.0),
child: TextFormField(
autofocus: false,
decoration: const InputDecoration(
labelText: 'Email:',
labelStyle: TextStyle(fontSize: 20.0),
border: OutlineInputBorder(),
errorStyle:
TextStyle(color: Colors.black26, fontSize: 15.0),
),
controller: emailController,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please Enter Email';
} else if (!value.contains('#')) {
return 'Please Enter Valid Email';
}
return null;
}),
),
Container(
margin: const EdgeInsets.symmetric(vertical: 10.0),
child: TextFormField(
autofocus: false,
obscureText: true,
decoration: const InputDecoration(
labelText: 'Password',
labelStyle: TextStyle(fontSize: 20.0),
border: OutlineInputBorder(),
errorStyle:
TextStyle(color: Colors.black26, fontSize: 15.0),
),
controller: passwordController,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please Enter Password';
}
return null;
},
),
),
Container(
margin: const EdgeInsets.symmetric(vertical: 20.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
setState(() {
email = emailController.text;
password = passwordController.text;
});
userLogin();
}
},
child: const Text(
'Login',
style: TextStyle(fontSize: 18.0),
),
),
TextButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ForgotPass(),
),
);
},
child: const Text(
'Forget Password ?',
style: TextStyle(
fontSize: 12.0,
),
),
)
],
),
),
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('Do Not Have Account ?'),
TextButton(
onPressed: () {
Navigator.pushAndRemoveUntil(
context,
PageRouteBuilder(
pageBuilder: (context, a, b) => Signup(),
transitionDuration: const Duration(seconds: 0),
),
(route) => false);
},
child: const Text('Signup'),
),
],
),
),
],
),
),
),
);
}
}
Iused these packages
firebase_core: ^1.5.0
firebase_auth: ^3.0.2
I searched a lot and found a lot of codes and This code is the best I've found
please i need help quickly
I think you have to add (keep the auth like it is) cloud firestore and set a doc for each user contains his name , last name , job , profile pic etc...
so every user will have doc on cloud firestore and user on Auth
some sources :
to set the user in singUp page :
https://petercoding.com/firebase/2020/04/04/using-cloud-firestore-in-flutter/

Validating TextformField with two different key in Flutter

I'm trying to validate two different TextFormFields in two widgets (One for Email, another one for password) with a single _formkey in a flutter. it gave me this error: Multiple widgets used the same GlobalKey. So defined two _formkey but the problem is Flutter form validators don't validate, simultaneously:
class _RegisterState extends State<Register> {
String email = "";
String password = "";
String error = "";
final _formKey1 = GlobalKey<FormState>();
final _formKey2 = GlobalKey<FormState>();
// bool _rememberMe = false;
Widget _buildEmailTF() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Email',
style: kLabelStyle,
),
SizedBox(height: 10.0),
Form(
key: _formKey1,
child: Container(
alignment: Alignment.centerLeft,
decoration: kBoxDecorationStyle,
height: 60.0,
child: TextFormField(
validator: (value) => value.isEmpty ? "Enter an Email" : null,
onChanged: (value) {
setState(() {
email = value;
});
},
style: TextStyle(
color: Colors.white,
fontFamily: 'OpenSans',
),
decoration: InputDecoration(
border: InputBorder.none,
contentPadding: EdgeInsets.only(top: 14.0),
prefixIcon: Icon(
Icons.email,
color: Colors.white,
),
hintText: 'Enter your Email',
hintStyle: kHintTextStyle,
),
),
),
),
],
);
}
Widget _buildPasswordTF() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Password',
style: kLabelStyle,
),
SizedBox(height: 10.0),
Form(
key: _formKey2,
child: Container(
alignment: Alignment.centerLeft,
decoration: kBoxDecorationStyle,
height: 60.0,
child: TextFormField(
validator: (value) =>
value.length < 6 ? "More than 6 Character" : null,
onChanged: (value) {
setState(() {
password = value;
});
},
obscureText: true,
style: TextStyle(
color: Colors.white,
fontFamily: 'OpenSans',
),
decoration: InputDecoration(
border: InputBorder.none,
contentPadding: EdgeInsets.only(top: 14.0),
prefixIcon: Icon(
Icons.lock,
color: Colors.white,
),
hintText: 'Enter your Password',
hintStyle: kHintTextStyle,
),
),
),
),
],
);
}
and then :
onPressed: () async {
if (_formKey1.currentState.validate() &&
_formKey2.currentState.validate()) {
dynamic result =
await _auth.signUpWithEmailandPassword(email, password);
if (result == null) {
setState(() => error = "Something is wrong");
}
}
},
Just remember that you need one Form Widget above in the widget Tree.
And thus you can use the _formKey to validate multiple TextFormField below in the Widget Tree.
Modified Code
class _RegisterPageState extends State<RegisterPage> {
String email = "";
String password = "";
String error = "";
final _formKey1 = GlobalKey<FormState>();
// final _formKey2 = GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Form(
key: _formKey1,
child: Container(
child: Column(
children: [
_buildEmailTF(),
SizedBox(
height: 20,
),
_buildPasswordTF(),
FlatButton(
onPressed: () async {
if (_formKey1.currentState.validate()) {
// dynamic result = await _auth.signUpWithEmailandPassword(
// email, password);
// if (result == null) {
// setState(() => error = "Something is wrong");
// }
print('DOne Working');
}
},
child: Text(
'Done',
))
],
),
),
),
);
}
// bool _rememberMe = false;
Widget _buildEmailTF() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Email',
),
SizedBox(height: 10.0),
Container(
alignment: Alignment.centerLeft,
height: 60.0,
child: TextFormField(
validator: (value) => value.isEmpty ? "Enter an Email" : null,
onChanged: (value) {
setState(() {
email = value;
});
},
style: TextStyle(
color: Colors.white,
fontFamily: 'OpenSans',
),
decoration: InputDecoration(
border: InputBorder.none,
contentPadding: EdgeInsets.only(top: 14.0),
prefixIcon: Icon(
Icons.email,
color: Colors.white,
),
hintText: 'Enter your Email',
),
),
),
],
);
}
Widget _buildPasswordTF() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Password',
),
SizedBox(height: 10.0),
Container(
alignment: Alignment.centerLeft,
height: 60.0,
child: TextFormField(
validator: (value) =>
value.length < 6 ? "More than 6 Character" : null,
onChanged: (value) {
setState(() {
password = value;
});
},
obscureText: true,
style: TextStyle(
color: Colors.white,
fontFamily: 'OpenSans',
),
decoration: InputDecoration(
border: InputBorder.none,
contentPadding: EdgeInsets.only(top: 14.0),
prefixIcon: Icon(
Icons.lock,
color: Colors.white,
),
hintText: 'Enter your Password',
),
),
),
],
);
}
}
I/flutter (24750): DOne Working

How to make wrap content for ListView

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