I am new to flutter and i am working on a result processing and record keeping system in the result processing part i have a form that takes in some details about the students like session, level, course code(It's for a university). now i have a collection in firebase of the levels and sessions in the department i am using for a case study and would like to check that the lecturer input corresponds or matches what is in the database.I am using a textformfield but i don't know how to validate the input with what is in firebase database. This is my code for the form. Thanks in advance for the help
class ScoreSheetPage extends StatefulWidget {
#override
State<ScoreSheetPage> createState() => _ScoreSheetPageState();
}
class _ScoreSheetPageState extends State<ScoreSheetPage> {
final formKey = GlobalKey<FormState>();
TextEditingController currentSession = TextEditingController();
TextEditingController currentLevelYear = TextEditingController();
TextEditingController matriculationNumber = TextEditingController();
TextEditingController currentSemester = TextEditingController();
TextEditingController courseCode = TextEditingController();
TextEditingController studentMarks1 = TextEditingController();
TextEditingController studentMarks2 = TextEditingController();
TextEditingController studentMarks3 = TextEditingController();
TextEditingController studentMarks4 = TextEditingController();
#override
Widget build(BuildContext context) {
final double height = MediaQuery.of(context).size.height;
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
return Scaffold(
backgroundColor: Colors.white,
body: SafeArea(
child: SingleChildScrollView(
child: Column(
children: [
Stack(
children: [
Container(
height: 230,
decoration: BoxDecoration(color: Color(0xFF363f93)),
),
SizedBox(
height: 100,
),
Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
alignment: Alignment.bottomCenter,
child: Text(
"RHEMA UNIVERSITY RESULT CALCULATION SYSTEM",
textAlign: TextAlign.center,
style: kHeading,
),
),
Text(
"Welcome",
textAlign: TextAlign.center,
style: kHeading,
),
],
),
)
],
),
Container(
alignment: Alignment.topLeft,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Form(
key: formKey,
child: Column(
children: [
Text(
"Please fill in the required information",
style: TextStyle(
color: Color(0xFF363f93),
fontSize: 30,
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.start,
),
SizedBox(
height: height * 0.04,
),
TextFormField(
controller: currentSession,
decoration: InputDecoration(
labelText:
"Enter current session, use format(1234-1234)"),
validator: (value) {
if (value!.isEmpty ||
!RegExp(r'^([0-9]{4}[-][0-9]{4})+$')
.hasMatch(value)) {
return "Enter correct session number";
} else {
return null;
}
},
),
SizedBox(
height: height * 0.04,
),
TextFormField(
controller: currentLevelYear,
decoration: InputDecoration(
labelText: "Enter Current Level/year"),
validator: (value) {
if (value!.isEmpty ||
!RegExp(r'^([0-9]{3})+$').hasMatch(value)) {
return "Enter correct level and year";
} else {
return null;
}
},
),
SizedBox(
height: height * 0.04,
),
TextFormField(
controller: matriculationNumber,
decoration: InputDecoration(
labelText:
"Enter student's matriculation number, use format(RU-CSC-19-202)"),
validator: (value) {
if (value!.isEmpty ||
!RegExp(r'^[A-Z]{2}[-][A-Z]{3}[-][0-9]{2}[-][0-9]{3}')
.hasMatch(value)) {
return "Enter correct Matriculation Number";
} else {
return null;
}
},
),
SizedBox(
height: height * 0.04,
),
TextFormField(
controller: currentSemester,
decoration: InputDecoration(
labelText: "Enter current semester"),
validator: (value) {
if (value!.isEmpty ||
!RegExp(r'^[a-z,A-Z]+$').hasMatch(value)) {
return "Enter correct name";
} else {
return null;
}
},
),
SizedBox(
height: height * 0.04,
),
TextFormField(
controller: studentMarks1,
decoration: InputDecoration(
labelText: "Enter score for attendance"),
validator: (value) {
if (value!.isEmpty ||
!RegExp(r'^[0-9]+$').hasMatch(value)) {
return "Enter correct score";
} else {
return null;
}
},
),
SizedBox(
height: height * 0.05,
),
TextFormField(
controller: studentMarks2,
decoration: InputDecoration(
labelText: "Enter score for assignment"),
validator: (value) {
if (value!.isEmpty ||
!RegExp(r'^[0-9]+$').hasMatch(value)) {
return "Enter correct score";
} else {
return null;
}
},
),
SizedBox(
height: height * 0.05,
),
TextFormField(
controller: studentMarks3,
decoration: InputDecoration(
labelText: "Enter score for test"),
validator: (value) {
if (value!.isEmpty ||
!RegExp(r'^[0-9]+$').hasMatch(value)) {
return "Enter correct score";
} else {
return null;
}
},
),
SizedBox(
height: height * 0.05,
),
TextFormField(
controller: studentMarks4,
decoration: InputDecoration(
labelText: "Enter Score for exams"),
validator: (value) {
if (value!.isEmpty ||
!RegExp(r'^[0-9]+$').hasMatch(value)) {
return "Enter correct score";
} else {
return null;
}
},
),
SizedBox(
height: height * 0.05,
),
GestureDetector(
child: Container(
alignment: Alignment.center,
width: 500,
child: SizedBox(
height: 50,
width: double.infinity,
child: ElevatedButton(
style: ButtonStyle(
foregroundColor:
MaterialStateProperty.all<Color>(
Colors.black),
backgroundColor:
MaterialStateProperty.all(
Colors.black),
shape: MaterialStateProperty.all<
RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(
1000))),
),
child: Text("Submit", style: kHeading),
onPressed: () {
if (formKey.currentState!.validate()) {
var finalScore = int.parse(
studentMarks2.text) +
int.parse(studentMarks3.text) +
int.parse(studentMarks4.text);
Map<String, dynamic> data = {
"Attendance": studentMarks1.text,
"Assignment": studentMarks2.text,
"Test Score": studentMarks3.text,
"Examination Score":
studentMarks4.text,
"final score": finalScore
};
final docUser = FirebaseFirestore
.instance
.collection("Exam Scores")
.doc(
"${currentLevelYear.text} Level")
.collection(
matriculationNumber.text)
.doc(
"${currentSemester.text} semester")
.collection(courseCode.text)
.doc("Scores");
docUser.set(data);
}
}),
)),
),
SizedBox(
height: 15,
),
TextButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Homepage()));
},
child: Text(
"Go back to home page",
style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,
),
)),
],
),
),
)),
],
),
),
),
);
}
}
Textformfield will work for you. You just need to check the data type required for the firebase and you can also add a validator in the Textformfield and pass pass regex to it. Textformfield will valid the input data.
Related
This is a part of a project regarding feedback forms.
I already manage to create the validation form properly thanks to the answers here in StackOverflow developers.
But the problem is creating this regular expression which seems to not work on the validation form. I found in flutter docs the Iterable but I do not know how can I implement it on the dart page.
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
class SimpleDialog extends StatelessWidget {
// ignore: prefer_typing_uninitialized_variables
final title;
const SimpleDialog(this.title, {super.key});
#override
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('Alert'),
content: Text(title),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('OK'))
],
);
}
}
class FeedbackPage extends StatefulWidget {
const FeedbackPage({super.key});
#override
State<FeedbackPage> createState() => _FeedbackPageState();
}
class _FeedbackPageState extends State<FeedbackPage> {
final nameOfuser = TextEditingController();
final emailOfuser = TextEditingController();
final messageOfuser = TextEditingController();
final _formKey = GlobalKey<FormState>();
List<bool> isTypeSelected = [false, false, false, true, true];
#override
Widget build(BuildContext context) {
return Scaffold(
// AppBar para sa taas ng design
appBar: AppBar(
centerTitle: true,
title: const Text(
"PicLeaf",
style: TextStyle(
color: Color.fromRGBO(102, 204, 102, 1.0),
fontWeight: FontWeight.bold),
),
backgroundColor: Colors.white,
shadowColor: const Color.fromARGB(255, 95, 94, 94),
),
//body of the application
backgroundColor: const Color(0xffeeeeee),
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
const SizedBox(
height: 20,
),
const Text(
"Feedback",
style: TextStyle(
fontSize: 30.0,
fontFamily: 'RobotoBold',
fontWeight: FontWeight.bold,
color: Color.fromRGBO(102, 204, 102, 1.0)),
),
const Text(
"Give us your feedback!",
style: TextStyle(
fontSize: 18.0,
fontFamily: 'RobotoMedium',
),
),
const SizedBox(
height: 20,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 32.0),
child: Form(
key: _formKey,
child: Column(
children: <Widget>[
const SizedBox(height: 16.0),
TextFormField(
controller: nameOfuser,
decoration: const InputDecoration(
filled: true,
fillColor: Colors.white,
hintText: "Name",
border: OutlineInputBorder(),
),
validator: (nameOfuser) {
if (nameOfuser == null || nameOfuser.isEmpty) {
return 'Please enter your Name';
}
return null;
},
),
const SizedBox(height: 8.0),
TextFormField(
controller: emailOfuser,
decoration: const InputDecoration(
filled: true,
fillColor: Colors.white,
hintText: "Email",
border: OutlineInputBorder(),
),
validator: (emailOfuser) {
if (emailOfuser == null || emailOfuser.isEmpty) {
String emailOfuser1 = emailOfuser.toString();
String pattern = r'\w+#\w+\.\w+';
if (RegExp(pattern).hasMatch(emailOfuser1)) {
return 'Please enter your Email Properly';
} else {
return 'Please enter your Email';
}
}
return null;
},
),
const SizedBox(height: 8.0),
TextFormField(
controller: messageOfuser,
maxLines: 6,
decoration: const InputDecoration(
filled: true,
fillColor: Colors.white,
hintText: "Message",
border: OutlineInputBorder(),
),
validator: (messageOfuser) {
if (messageOfuser == null || messageOfuser.isEmpty) {
return 'Please enter your Message';
}
return null;
},
),
const SizedBox(height: 8.0),
MaterialButton(
height: 50.0,
minWidth: double.infinity,
color: const Color.fromRGBO(102, 204, 102, 1.0),
onPressed: () {
if (_formKey.currentState!.validate()) {
showDialog(
context: context,
builder: (BuildContext context) {
return const SimpleDialog(
'Feedback Submitted');
});
Map<String, dynamic> data = {
"Name": nameOfuser.text,
"Email": emailOfuser.text,
"Message": messageOfuser.text,
"Time": FieldValue.serverTimestamp(),
};
setState(() {
nameOfuser.clear();
emailOfuser.clear();
messageOfuser.clear();
});
FirebaseFirestore.instance
.collection("FeedbackMessages")
.add(data);
}
},
child: const Text(
"SUBMIT",
style: TextStyle(
fontFamily: 'RobotoBold',
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
const SizedBox(
height: 10,
),
Container(
padding: const EdgeInsets.fromLTRB(20, 20, 20, 10),
child: const Text(
'Contact Us!',
style: TextStyle(
fontSize: 30,
fontFamily: 'RobotoBold',
color: Color.fromRGBO(102, 204, 102, 1.0)),
textAlign: TextAlign.center,
),
),
Column(
children: <Widget>[
Container(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
margin: const EdgeInsets.symmetric(horizontal: 0),
child: TextButton.icon(
// <-- TextButton
onPressed: () {},
icon: const Icon(
Icons.facebook,
color: Colors.black,
size: 35.0,
),
label: const Text(
'facebook.com/picleaf',
style: TextStyle(fontFamily: 'RobotoMedium'),
),
style: TextButton.styleFrom(
foregroundColor: Colors.black,
),
),
),
Container(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 10),
margin: const EdgeInsets.symmetric(horizontal: 0),
child: TextButton.icon(
// <-- TextButton
onPressed: () {},
icon: const Icon(
Icons.email,
color: Colors.black,
size: 35.0,
),
label: const Text(
'picleaf#gmail.com',
style: TextStyle(fontFamily: 'RobotoMedium'),
),
style: TextButton.styleFrom(
foregroundColor: Colors.black,
),
)),
],
)
],
),
),
),
],
),
));
}
}
You can use this validator:
validator: (emailOfuser) {
if (emailOfuser == null || emailOfuser.isEmpty) {
return 'Please enter your Email';
} else if (emailOfuser.isNotEmpty) {
String emailOfuser1 = emailOfuser.toString();
String pattern = r'\w+#\w+\.\w+';
if (RegExp(pattern).hasMatch(emailOfuser1) == false) {
return 'Please enter your Email Properly';
}
}
return null;
},
try to implement like this:
import 'package:flutter/material.dart';
class EmailValidationForm extends StatefulWidget {
const EmailValidationForm({Key? key}) : super(key: key);
#override
State<EmailValidationForm> createState() => _EmailValidationFormState();
}
class _EmailValidationFormState extends State<EmailValidationForm> {
final GlobalKey<FormState> formKey = GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Email Validation'),
),
body: Form(
key: formKey,
child: Column(
children: [
TextFormField(
autofocus: false,
maxLength: 300,
keyboardType: TextInputType.emailAddress,
autocorrect: false,
validator: (email) {
if (email!.isEmpty) {
return 'required field';
} else if (email.trim().contains(' ')) {
return 'contain space';
} else if (!emailValid(email)) {
return 'invalid email';
}
return null;
},
onSaved: (email) {
return debugPrint(email);
},
),
ElevatedButton(
onPressed: () {
if (formKey.currentState!.validate()) {
formKey.currentState!.save();
}
},
child: const Text('Validate')),
],
),
),
);
}
}
bool emailValid(String email) {
final RegExp regex = RegExp(
r"^(([^<>()[\]\\.,;:\s#\']+(\.[^<>()[\]\\.,;:\s#\']+)*)|(\'.+\'))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$");
return regex.hasMatch(email.trim());
}
So i'm building an app that has a login (i'm knew to flutter so i'm just getting code on youtube and try to add it) and it's supposed to have a bottom bar that leeds to de home page and the profile screen. In the profile screen he can log out.
The problem is, the app was all good, but I tried to add the bottom bar, (i had to add a AuthWrapper()
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:pap_test/tabs_screen.dart';
import 'login_signup/screens/login_screen.dart';
class AuthWrapper extends StatelessWidget {
const AuthWrapper({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
final FirebaseAuth _auth = FirebaseAuth.instance;
return StreamBuilder(
stream: _auth.authStateChanges(),
builder: (context, user) {
User? _user = user.data as User?;
if (_user != null) {
return const TabsScreen();
} else {
return const LoginScreen();
}
},
);
}
}
That takes to the home page and the profile page.
// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables
import 'package:flutter/material.dart';
import 'disciplinas/disciplinas_screen.dart';
import 'login_signup/screens/home_screen.dart';
class TabsScreen extends StatefulWidget {
const TabsScreen({Key? key}) : super(key: key);
#override
_TabsScreenState createState() => _TabsScreenState();
}
class _TabsScreenState extends State<TabsScreen> {
final List<Widget> _pages = [
DisciplinasScreen(),
HomeScreen(),
];
int _selectedPageIndex = 0;
void _selectPage(int index) {
setState(() {
_selectedPageIndex = index;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
'',
), //seja qual for a opção do bottom bar selecionada ele irá dar o titulo que indicamos e mesmo para a outra página
),
body: _pages[_selectedPageIndex],
bottomNavigationBar: BottomNavigationBar(
onTap: _selectPage,
backgroundColor: Colors.black,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.account_circle_outlined),
label: 'Profile',
),
],
),
);
}
}
the problem is that when i'm in the app, when i rebuild it, the bottom bar is there, but the app bar gets all weird, and when i go to the profile screen, log out and then sign in the app bar gets back to normal but the bottom bar isn't there.
the rotes in the main
routes: {
'/': (ctx) => AuthWrapper(),
DisciplinaModuloScreen.routeName: (ctx) => DisciplinaModuloScreen(),
DownloadScreen.routeName: (ctx) => DownloadScreen(),
UploadResumoScreen.routeName: (ctx) => UploadResumoScreen(),
},
the log in
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../../disciplinas/disciplinas_screen.dart';
import '../screens/registration_screen.dart';
class LoginScreen extends StatefulWidget {
const LoginScreen({Key? key}) : super(key: key);
#override
_LoginScreenState createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
//form key
final _formKey = GlobalKey<FormState>();
//editing controller
final TextEditingController emailController = new TextEditingController();
final TextEditingController passwordController = new TextEditingController();
// firebase
final _auth = FirebaseAuth.instance;
// string for displaying the error Message
String? errorMessage;
#override
Widget build(BuildContext context) {
// email field
final emailField = TextFormField(
style: Theme.of(context).textTheme.headline6,
autofocus: false,
controller: emailController,
keyboardType: TextInputType.emailAddress,
validator: (value) {
if (value!.isEmpty) {
return ('Email obrigatório');
}
// reg expression for email validation
if (!RegExp("^[a-zA-Z0-9+_.-]+#[a-zA-Z0-9.-]+.[a-z]").hasMatch(value)) {
return ('Insira um email válifo');
}
return null;
},
onSaved: (value) {
emailController.text = value!;
},
textInputAction: TextInputAction.next,
decoration: InputDecoration(
prefixIcon: Icon(
Icons.mail,
color: Color.fromARGB(255, 28, 209, 216),
),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
hintText: 'Email',
hintStyle: Theme.of(context).textTheme.headline2,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
//borderSide: BorderSide(color: Colors.pink, width: 5.0),
),
),
);
// password field
final passwordField = TextFormField(
style: Theme.of(context).textTheme.headline6,
autofocus: false,
controller: passwordController,
obscureText: true,
validator: (value) {
RegExp regex = new RegExp(r'^.{6,}$');
if (value!.isEmpty) {
return ('Insira uma password');
}
if (!regex.hasMatch(value)) {
return ('Utilize 6 ou mais carateres');
}
},
onSaved: (value) {
passwordController.text = value!;
},
textInputAction: TextInputAction.done,
decoration: InputDecoration(
prefixIcon: Icon(
Icons.vpn_key,
color: Color.fromARGB(255, 28, 209, 216),
),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
hintText: 'Password',
hintStyle: Theme.of(context).textTheme.headline2,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: BorderSide(color: Colors.pink, width: 5.0),
),
),
);
// login field
final loginButton = Material(
elevation: 5,
borderRadius: BorderRadius.circular(15),
color: Color.fromARGB(255, 28, 209, 216),
child: MaterialButton(
padding: EdgeInsets.fromLTRB(20, 15, 20, 15),
minWidth: MediaQuery.of(context).size.width,
onPressed: () {
signIn(emailController.text, passwordController.text);
},
child: Text(
'Login',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.headline6,
),
),
);
return Scaffold(
// backgroundColor: ,
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,
child: Image.asset(
'assets/images/owl_white.png',
fit: BoxFit.contain,
),
),
emailField,
SizedBox(height: 15),
passwordField,
SizedBox(height: 30),
loginButton,
SizedBox(height: 15),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Não tens conta? ',
style: Theme.of(context).textTheme.bodyText1,
),
GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => RegistrationScreen(),
),
);
},
child: Text(
'SignUp',
style: Theme.of(context).textTheme.bodyText2,
),
)
],
)
],
),
),
),
),
),
),
);
}
void signIn(String email, String password) async {
if (_formKey.currentState!.validate()) {
try {
await _auth
.signInWithEmailAndPassword(email: email, password: password)
.then((uid) => {
Fluttertoast.showToast(msg: "Login Successful"),
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (context) => DisciplinasScreen())),
});
} on FirebaseAuthException catch (error) {
switch (error.code) {
case "invalid-email":
errorMessage = "Your email address appears to be malformed.";
break;
case "wrong-password":
errorMessage = "Your password is wrong.";
break;
case "user-not-found":
errorMessage = "User with this email doesn't exist.";
break;
case "user-disabled":
errorMessage = "User with this email has been disabled.";
break;
case "too-many-requests":
errorMessage = "Too many requests";
break;
case "operation-not-allowed":
errorMessage = "Signing in with Email and Password is not enabled.";
break;
default:
errorMessage = "An undefined Error happened.";
}
Fluttertoast.showToast(msg: errorMessage!);
print(error.code);
}
}
}
}
the sign up
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../../disciplinas/disciplinas_screen.dart';
import '../models/user_model.dart';
class RegistrationScreen extends StatefulWidget {
RegistrationScreen({Key? key}) : super(key: key);
#override
State<RegistrationScreen> createState() => _RegistrationScreenState();
}
class _RegistrationScreenState extends State<RegistrationScreen> {
final _auth = FirebaseAuth.instance;
// our form key
final _formKey = GlobalKey<FormState>();
//editing Controller
final firstNameEditingController = new TextEditingController();
// final secondNameEditingController = new TextEditingController();
final emailEditingController = new TextEditingController();
final passwordEditingController = new TextEditingController();
final confirmPassWordEditingController = new TextEditingController();
String? errorMessage;
#override
Widget build(BuildContext context) {
// first name field
final firstNameField = TextFormField(
style: Theme.of(context).textTheme.headline6,
autofocus: false,
controller: firstNameEditingController,
keyboardType: TextInputType.name,
validator: (value) {
RegExp regex = new RegExp(r'^.{3,}$');
if (value!.isEmpty) {
return ('Insira um Nome');
}
if (!regex.hasMatch(value)) {
return ('Utilize 3 ou mais carateres');
}
return null;
},
onSaved: (value) {
firstNameEditingController.text = value!;
},
textInputAction: TextInputAction.next,
decoration: InputDecoration(
prefixIcon: Icon(
Icons.account_circle,
color: Color.fromARGB(255, 28, 209, 216),
),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
hintText: 'Primeiro Nome',
hintStyle: Theme.of(context).textTheme.headline2,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
//borderSide: BorderSide(color: Colors.pink, width: 5.0),
),
),
);
// email field
final emailField = TextFormField(
style: Theme.of(context).textTheme.headline6,
autofocus: false,
controller: emailEditingController,
keyboardType: TextInputType.emailAddress,
validator: (value) {
if (value!.isEmpty) {
return ('Email obrigatório');
}
// reg expression for email validation
if (!RegExp("^[a-zA-Z0-9+_.-]+#[a-zA-Z0-9.-]+.[a-z]").hasMatch(value)) {
return ('Insira um email válifo');
}
return null;
},
onSaved: (value) {
emailEditingController.text = value!;
},
textInputAction: TextInputAction.next,
decoration: InputDecoration(
prefixIcon: Icon(
Icons.mail,
color: Color.fromARGB(255, 28, 209, 216),
),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
hintText: 'Email',
hintStyle: Theme.of(context).textTheme.headline2,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
//borderSide: BorderSide(color: Colors.pink, width: 5.0),
),
),
);
// password field
final passwordField = TextFormField(
style: Theme.of(context).textTheme.headline6,
autofocus: false,
controller: passwordEditingController,
obscureText: true,
validator: (value) {
RegExp regex = new RegExp(r'^.{6,}$');
if (value!.isEmpty) {
return ('Insira uma password');
}
if (!regex.hasMatch(value)) {
return ('Utilize 6 ou mais carateres');
}
},
onSaved: (value) {
passwordEditingController.text = value!;
},
textInputAction: TextInputAction.next,
decoration: InputDecoration(
prefixIcon: Icon(
Icons.vpn_key,
color: Color.fromARGB(255, 28, 209, 216),
),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
hintText: 'Password',
hintStyle: Theme.of(context).textTheme.headline2,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
//borderSide: BorderSide(color: Colors.pink, width: 5.0),
),
),
);
// confirm password field
final confirmPasswordField = TextFormField(
style: Theme.of(context).textTheme.headline6,
autofocus: false,
controller: confirmPassWordEditingController,
obscureText: true,
validator: (value) {
if (confirmPassWordEditingController.text !=
passwordEditingController.text) {
return ('As palavras-passe não coincidem. Tente novamente.');
}
return null;
},
onSaved: (value) {
confirmPassWordEditingController.text = value!;
},
textInputAction: TextInputAction.done,
decoration: InputDecoration(
prefixIcon: Icon(
Icons.vpn_key,
color: Color.fromARGB(255, 28, 209, 216),
),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
hintText: 'Confirma a Password',
hintStyle: Theme.of(context).textTheme.headline2,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
//borderSide: BorderSide(color: Colors.pink, width: 5.0),
),
),
);
// signup field
final signUpButton = Material(
elevation: 5,
borderRadius: BorderRadius.circular(15),
color: Color.fromARGB(255, 28, 209, 216),
child: MaterialButton(
padding: EdgeInsets.fromLTRB(20, 15, 20, 15),
minWidth: MediaQuery.of(context).size.width,
onPressed: () {
signUp(emailEditingController.text, passwordEditingController.text);
},
child: Text(
'Sign up',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.headline6,
),
),
);
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
leading: IconButton(
icon: Icon(
Icons.arrow_back,
color: Color.fromARGB(255, 28, 209, 216),
),
onPressed: () {
// passing this to our root
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,
child: Image.asset(
'assets/images/owl_white.png',
fit: BoxFit.contain,
),
),
SizedBox(height: 0),
firstNameField,
// SizedBox(height: 15),
// secondNameField,
SizedBox(height: 15),
emailField,
SizedBox(height: 15),
passwordField,
SizedBox(height: 15),
confirmPasswordField,
SizedBox(height: 15),
signUpButton,
],
),
),
),
),
),
),
);
}
void signUp(String email, String password) async {
if (_formKey.currentState!.validate()) {
try {
await _auth
.createUserWithEmailAndPassword(email: email, password: password)
.then((value) => {postDetailsToFirestore()})
.catchError((e) {
Fluttertoast.showToast(msg: e!.message);
});
} on FirebaseAuthException catch (error) {
switch (error.code) {
case "invalid-email":
errorMessage = "Your email address appears to be malformed.";
break;
case "wrong-password":
errorMessage = "Your password is wrong.";
break;
case "user-not-found":
errorMessage = "User with this email doesn't exist.";
break;
case "user-disabled":
errorMessage = "User with this email has been disabled.";
break;
case "too-many-requests":
errorMessage = "Too many requests";
break;
case "operation-not-allowed":
errorMessage = "Signing in with Email and Password is not enabled.";
break;
default:
errorMessage = "An undefined Error happened.";
}
Fluttertoast.showToast(msg: errorMessage!);
print(error.code);
}
}
}
postDetailsToFirestore() async {
// calling our firestore
// calling our model
// sending these values
FirebaseFirestore firebaseFirestore = FirebaseFirestore.instance;
User? user = _auth.currentUser;
UserModel userModel = UserModel();
// writing all the values
userModel.email = user!.email;
userModel.uid = user.uid;
userModel.firstName = firstNameEditingController.text;
await firebaseFirestore
.collection('users')
.doc(user.uid)
.set(userModel.toMap());
Fluttertoast.showToast(msg: 'Conta criada :)');
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (context) => DisciplinasScreen()),
(route) => false);
}
}
all the code is here https://drive.google.com/drive/folders/1TlFibzTPXph_mAzyeS3CADTYxsWF3YIv?usp=sharing
a video of what is happening
https://drive.google.com/file/d/1yLMeQ4xxanmtcVQSERCWwf0uY_JXyJ5b/view?usp=sharing
the database for the users
Given that once a user logs in they are supposed to be sent to TabsScreen as per your authwrapper return const TabsScreen();
As per your code once a user is signed in you send them to DisciplinasScreen
Fluttertoast.showToast(msg: "Login Successful"),
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (context) => DisciplinasScreen())),
Once a user logs in send them to AUth wrapper and let authwrapper figure out where to nav the user
Fluttertoast.showToast(msg: "Login Successful"),
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (context) =>TabsScreen())),
Navigating them to DisciplinasScreen causes the 'weird' stuff you are seeing as its built to work within TabsScreen
Warning: Ignoring header X-Firebase-Locale because its value was null.
I'm getting this warning while signing up a user in firebase. When i signup in my app it doesn't get added into firebase?(I'm working on flutter in VS Code). Code for my Signup Page is being written below:
class Signup extends StatefulWidget {
Signup ({ Key? key }) : super(key: key);
#override
_SignupState createState() => _SignupState();
}
class _SignupState extends State<Signup> {
final _formKey = GlobalKey<FormState>();
var email = " ";
var password = " ";
var confirmPassword = " ";
final emailController = TextEditingController();
final passwordController = TextEditingController();
final confirmPasswordController = TextEditingController();
#override
void dispose()
{
emailController.dispose();
passwordController.dispose();
confirmPasswordController.dispose();
super.dispose();
}
registration() async{
if(password == confirmPassword)
{
try{
await FirebaseAuth.instance.createUserWithEmailAndPassword(email: email, password: password);
}catch(e){}
}
else{
print("Password doesn't match");
}
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('User Signup'),
),
body : Form(
key: _formKey,
child: Padding(
padding: EdgeInsets.symmetric(vertical: 20, horizontal: 30),
child: ListView(
children: [
Container(
margin: EdgeInsets.symmetric(vertical: 10.0),
child: TextFormField(
autofocus: false,
decoration: InputDecoration(
labelText: 'Email: ',
labelStyle: TextStyle(fontSize: 20.0),
border: OutlineInputBorder(),
errorStyle:
TextStyle(color: Colors.redAccent,
fontSize: 15),
),
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: EdgeInsets.symmetric(vertical: 10.0),
child: TextFormField(
autofocus: false,
obscureText: true,
decoration: InputDecoration(
labelText: 'Password: ',
labelStyle: TextStyle(fontSize: 20.0),
border: OutlineInputBorder(),
errorStyle:
TextStyle(color: Colors.redAccent,
fontSize: 15),
),
controller: passwordController,
validator: (value)
{
if(value==null || value.isEmpty)
{
return 'Please Enter Password';
}
return null;
},
)
),
Container(
margin: EdgeInsets.symmetric(vertical: 10.0),
child: TextFormField(
autofocus: false,
obscureText: true,
decoration: InputDecoration(
labelText: 'Confirm Password: ',
labelStyle: TextStyle(fontSize: 20.0),
border: OutlineInputBorder(),
errorStyle:
TextStyle(color: Colors.redAccent,
fontSize: 15),
),
controller: confirmPasswordController,
validator: (value)
{
if(value==null || value.isEmpty)
{
return 'Please Enter Password';
}
return null;
},
)
),
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
if(_formKey.currentState!.validate())
{
setState(() {
email = emailController.text;
password =passwordController.text;
confirmPassword = confirmPasswordController.text;
});
}
registration();
},
child: Text(
'Sign Up',
style: TextStyle(color: Colors.white, fontSize: 20),
)
)
],
),
),
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children:[
Text("Already have an Account? "),
TextButton(
onPressed: ()=>{
Navigator.pushReplacement(
context,
PageRouteBuilder(
pageBuilder:
(context, animation1, animation2)
=>LoginPage(),
transitionDuration: Duration(seconds:0),
)
),
},
child: Text('Login')
)
]
)
)
],
)
)
)
);
}
}
I'm expecting to get a user added in firebase after signing up through my app.
I am creating a app using flutter and firebase. but when i am trying to create a user instance it is showing this error:- "PlatformException(ERROR_INVALID_EMAIL, The email address is badly formatted., null)"
I am attaching the code.///////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
import 'package:chatbox/services/auth.dart';
import 'package:chatbox/services/database.dart';
import 'package:chatbox/views/chatRoom.dart';
import 'package:chatbox/widgets/widget.dart';
import 'package:flutter/material.dart';
class SignUp extends StatefulWidget {
final Function toggle;
SignUp(this.toggle);
#override
_SignUpState createState() => _SignUpState();
}
class _SignUpState extends State<SignUp> {
bool isLoading = false;
DatabaseMethods databaseMethods=new DatabaseMethods();
AuthMethods authMethods = new AuthMethods();
final formKey = GlobalKey<FormState>();
TextEditingController userNameTextEditingController =
new TextEditingController();
TextEditingController emailTextEditingController =
new TextEditingController();
TextEditingController passwordTextEditingController =
new TextEditingController();
signMeUp() async {
if(formKey.currentState.validate()) {
Map<String,String> userInfoMap={
"email": emailTextEditingController.text,
"name" : userNameTextEditingController.text,
};
setState(() {
isLoading =true;
});
authMethods.signUpWithEmailAndPassword(emailTextEditingController.text, passwordTextEditingController.text)
.then((val){
// print("${val.uid}");
databaseMethods.uploadUserInfo(userInfoMap);
Navigator.pushReplacement(context, MaterialPageRoute(
builder: (context)=>chatRoom(),
));
});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: appBarMain(context),
body: isLoading ? Container(
child: Center(child: CircularProgressIndicator()) ,
) : SingleChildScrollView(
child: Container(
height: MediaQuery.of(context).size.height - 50,
alignment: Alignment.bottomCenter,
padding: EdgeInsets.symmetric(horizontal: 24),
child: Column(mainAxisSize: MainAxisSize.min, children: [
Form(
key: formKey,
child: Column(
children: [
TextFormField(
validator: (val) {
return val.isEmpty || val.length < 2 ? "invalid" : null;
},
controller: userNameTextEditingController,
style: simpleTextstyle(),
decoration: textFieldInputDecoration("username"),
),
TextFormField(
validator: (val){
return RegExp(r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+#[a-zA-Z0-9]+\.[a-zA-Z]+").hasMatch(val) ? null : "Enter correct email";
},
controller: emailTextEditingController,
style: simpleTextstyle(),
decoration: textFieldInputDecoration("email"),
),
TextFormField(
validator: (val) {
return val.length < 6
? "Enter Password 6+ characters"
: null;
},
controller: passwordTextEditingController,
style: simpleTextstyle(),
obscureText: true,
decoration: textFieldInputDecoration("password"),
),
],
),
),
SizedBox(
height: 8,
),
Container(
alignment: Alignment.centerRight,
child: Container(
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Text(
"forget password",
style: simpleTextstyle(),
),
)),
SizedBox(
height: 8,
),
GestureDetector(
onTap: () {
signMeUp();
},
child: Container(
alignment: Alignment.center,
width: MediaQuery.of(context).size.width,
padding: EdgeInsets.symmetric(vertical: 20),
decoration: BoxDecoration(
gradient: LinearGradient(colors: [
const Color(0xff007EF4),
const Color(0xff2A75BC)
]),
borderRadius: BorderRadius.circular(40)),
child: Text(
"Sign up",
style: TextStyle(color: Colors.white, fontSize: 17),
),
),
),
SizedBox(
height: 8,
),
Container(
alignment: Alignment.center,
width: MediaQuery.of(context).size.width,
padding: EdgeInsets.symmetric(vertical: 20),
decoration: BoxDecoration(
color: Colors.white, borderRadius: BorderRadius.circular(40)),
child: Text(
"Sign up with google",
style: TextStyle(color: Colors.black, fontSize: 17),
),
),
SizedBox(
height: 8,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"Already have an account?",
style: meadiumTextstyle(),
),
GestureDetector(
onTap: (){
widget.toggle();
},
child: Container(
padding: EdgeInsets.symmetric(vertical: 8),
child: Text("Sign in Now",
style: TextStyle(
color: Colors.white,
fontSize: 17,
decoration: TextDecoration.underline,
)),
),
),
],
),
SizedBox(
height: 60,
),
]),
),
),
);
}
}
Assume email is correct
From issue https://github.com/FirebaseExtended/flutterfire/issues/1760#issuecomment-570766212 and https://github.com/FirebaseExtended/flutterfire/issues/1760#issuecomment-613303831
email text field value might contain white space
You can use emailTextEditingController.text.trim()
code snippet
authMethods.signUpWithEmailAndPassword(emailTextEditingController.text.trim(), passwordTextEditingController.text)
...
Map<String,String> userInfoMap={
"email": emailTextEditingController.text.trim(),
"name" : userNameTextEditingController.text,
};
You can also use package https://pub.dev/packages/email_validator to validate email
code snippet
import 'dart:core';
import 'package:email_validator/email_validator.dart';
void main() {
const String email = 'fredrik.eilertsen#gail.com';
final bool isValid = EmailValidator.validate(email);
print('Email is valid? ' + (isValid ? 'yes' : 'no'));
}
The error is because your email id is not in the correct format. Try editing your email id.
In your email validator add this.
Validator(val){
if(!val.contains("#")){
retrun enter a valid email}
else{ return null}
}
I wanted to know as to how can I submit the form which will print the user data from a previous page as well as the current page it is in? This will help me further when I am trying to update user data on firestore. I couldn't find a solution hence I would really appreciate whatever help I can get! :)
edit:
For anyone who didn't get what I was trying to say
I have the textfields of First Name, Last name and age in one page for which the user will press on the next button when done entering. In the final registration page which consists of email and password textfields contains the Register button which will register the user. I want to press Register on the final registration page which will print the data entered in the previous page as well as the current page. I wanted to know how can I achieve that so that later on I can update the user data to firestore
previous page
class UserDetails extends StatefulWidget {
#override
_UserDetailsState createState() => _UserDetailsState();
}
enum Gender{
Male, Female, Others
}
class _UserDetailsState extends State<UserDetails> {
String userFirstName;
String userLastName;
String user_age;
int group_value = -1;
Gender _gender = Gender.Male;
final formkeyDetails = GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
//final _userProvider = Provider.of<UserProvider>(context);
final _firstName = Container(
padding: EdgeInsets.only(left: 10, right: 10),
child: TextFormField(
autofocus: false,
keyboardType: TextInputType.text,
/*onChanged: (value){
_userProvider.changeFirstName(value);
},
*/
validator: (value) {
if(value.isEmpty)
{
return 'Field cannot be empty';
}
return null;
},
onSaved: (value)=> userFirstName = value,
decoration: InputDecoration(
hintText: 'Enter First Name',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)
),
),
),
);
final _lastName = Container(
padding: EdgeInsets.only(left: 10, right: 10),
child: TextFormField(
autofocus: false,
keyboardType: TextInputType.text,
/* onChanged: (value){
_userProvider.changeLastName(value);
}
,
*/
validator: (value) {
if(value.isEmpty)
{
return 'Field cannot be empty';
}
return null;
},
onSaved: (value)=> userLastName = value,
decoration: InputDecoration(
hintText: 'Enter Last Name',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)
),
),
),
);
final _userAge = Container(
padding: EdgeInsets.only(left: 10, right: 10),
child: TextFormField(
keyboardType: TextInputType.number,
autofocus: false,
/* onChanged: (value){
_userProvider.changeAge(value);
},
*/
validator: (value) {
if(value.isEmpty)
{
return 'Field cannot be empty';
}
return null;
},
onSaved: (value)=> user_age = value,
decoration: InputDecoration(
hintText: 'Enter Age',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)
),
),
),
);
final _male = Radio(
value: Gender.Male,
activeColor: Colors.black,
groupValue: _gender,
onChanged: (Gender value){
setState(() {
print(value);
_gender = value;
});
},
);
final _female = Radio(
activeColor: Colors.black,
value: Gender.Female,
groupValue: _gender,
onChanged: (Gender value){
setState(() {
print(value);
_gender = value;
});
},
);
final _others = Radio(
activeColor: Colors.black,
value: Gender.Others,
groupValue: _gender,
onChanged: (Gender value){
setState(() {
print(value);
_gender = value;
});
},
);
return Scaffold(
backgroundColor: Colors.yellow,
body: Container(
child: Form(
key: formkeyDetails,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("Register",
style: TextStyle(fontSize: 64.0, fontWeight: FontWeight.bold),),
SizedBox(height: 50,),
_firstName,
SizedBox(height: 20,),
_lastName,
SizedBox(height: 20,),
_userAge,
SizedBox(height: 30,),
Row(
crossAxisAlignment: CrossAxisAlignment.center ,
children: <Widget>[
Text(" Gender: ", style: TextStyle(fontSize: 20.0),),
_male,
Text("Male"),
_female,
Text("Female"),
_others,
Text("Others"),
],
),
Row(
crossAxisAlignment: CrossAxisAlignment.center ,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
FloatingActionButton.extended(
heroTag: "prev_button",
backgroundColor: Colors.yellow,
foregroundColor: Colors.black,
onPressed: ()=> Navigator.push(context, MaterialPageRoute(builder: (context)=>UserLogin())),
label: Text("Prev", style: TextStyle(fontWeight: FontWeight.bold),)
),
FloatingActionButton.extended(
heroTag: "next_button",
backgroundColor: Colors.yellow,
foregroundColor: Colors.black,
onPressed: ()=> Navigator.push(context, MaterialPageRoute(builder: (context)=>UserReg())),
label: Text("Next", style: TextStyle(fontWeight: FontWeight.bold),)
),
],
),
],
),
),
),
);
}
}
Current page (which will print the contents of the previous page as well)
class UserReg extends StatefulWidget {
UserReg({this.auth});
final BaseAuth auth;
#override
State<StatefulWidget> createState() => _UserRegState();
}
class _UserRegState extends State<UserReg> {
final formkey = GlobalKey<FormState>();
static String emailValidator(String value) {
Pattern pattern =
r'^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
RegExp regex = new RegExp(pattern);
if (!regex.hasMatch(value)) {
return 'Email format is invalid';
} else {
return null;
}
}
static String pwdValidator(String value) {
if (value.length <= 6) {
return 'Password must be longer than 8 characters';
} else {
return null;
}
}
bool _validateAndSave()
{
final form2 = formkey.currentState;
final form1 = formkeyDetails.currentState;
if(form2.validate())
{
form.save();
return true;
}
return false;
}
void _validateAndSubmit() async
{
if(_validateAndSave()) {
try {
String userId = await Auth().signUp(rEmail, rPass);
await Auth().sendEmailVerification();
formkey.currentState.reset();
print('Registered! $userId, sent email verification');
}
catch (e) {
print('Error: $e');
}
}
}
final notValidIcon = Icon(
Icons.error,
color: Colors.pink,
);
static String rEmail;
static String rPass;
#override
Widget build(BuildContext context) {
//final userProvider = Provider.of<UserProvider>(context);
final _regEmail = Container(
padding: EdgeInsets.only(left: 10, right: 10),
child: TextFormField(
keyboardType: TextInputType.emailAddress,
autofocus: false,
validator: (value) {
if(value.isEmpty)
{
return 'Email cannot be empty';
}
else
emailValidator(value);
return null;
},
/*onChanged: (value){
userProvider.changeEmail(value);
},
*/
onSaved: (value)=> rEmail = value,
decoration: InputDecoration(
hintText: 'Enter Email Address',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)
),
),
),
);
final _regpass = Container(
padding: EdgeInsets.only(left: 10, right: 10),
child: TextFormField(
obscureText: true,
autofocus: false,
validator: pwdValidator,
/*onChanged: (value){
userProvider.changePassword(value);
},
*/
onSaved: (value)=> rPass = value,
decoration: InputDecoration(
hintText: 'Enter password',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)
),
),
),
);
final _confPass = Container(
padding: EdgeInsets.only(left: 10, right: 10),
child: TextFormField(
obscureText: true,
autofocus: false,
validator: (value){
if(value != rPass)
{
return("Password does not match");
}
return pwdValidator(value);
},
/*
onChanged: (value){
userProvider.changePassword(value);
},
*/
onSaved: (value)=> rPass = value,
decoration: InputDecoration(
hintText: 'Enter password',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)
),
),
),
);
return new Scaffold(
resizeToAvoidBottomInset: true,
backgroundColor: Colors.yellow,
body: Container(
height: MediaQuery.of(context).size.height,
child: Form(
key: formkey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
SizedBox(height: MediaQuery.of(context).size.height *0.2,),
Text('Register',
style:TextStyle(
fontWeight: FontWeight.bold,
fontSize: 64,
),
),
SizedBox(height: 100,),
_regEmail,
SizedBox(height: 20,),
_regpass,
SizedBox(height:30),
//_confRegPass,
SizedBox(height: 30,),
FloatingActionButton.extended(
heroTag: "Register_Button",
backgroundColor: Colors.yellow,
foregroundColor: Colors.black,
onPressed: (){
_validateAndSubmit();
//userProvider.saveUser();
Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=>UserLogin()));
},
label: Text("Register", style: TextStyle(fontWeight: FontWeight.bold),)
),
SizedBox(height: 20,),
FlatButton(
child: Text('Already Registered? Sign in!'),
onPressed: ()=> Navigator.push(context, MaterialPageRoute(builder: (context)=>UserLogin())) ,
),
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
FloatingActionButton.extended(
heroTag: "prev_button1",
backgroundColor: Colors.yellow,
foregroundColor: Colors.black,
onPressed: ()=> Navigator.pop(context), //Navigator.push(context, MaterialPageRoute(builder: (context)=>UserDetails())),
label: Text("Prev", style: TextStyle(fontWeight: FontWeight.bold),)
),
],
),
],
),
),
),
);
}
}
Instead of directly going to the next page, you can validate the form in the current page itself using
onPressed: () {
// Validate returns true if the form is valid, otherwise false.
if (formKey.currentState.validate()) {
//Navigation Logic
}
}
And if you want the data from the previous page then you can refer to https://flutter.dev/docs/cookbook/navigation/passing-data