TextField State Management in Flutter - flutter

I am trying to create a note app. I am using a Textfield with a prefixicon and my problem is that if the user types something in the textfield and afterwards picks a date, then the textfield input is getting cleared. Any suggestions ?? Thanks in advance !
Here is tthe full code...
class AddTask extends StatefulWidget {
#override
_AddTaskState createState() => _AddTaskState();
}
class _AddTaskState extends State<AddTask> {
DateTime daytime;
#override
Widget build(BuildContext context) {
String newNoteTitle;
String newNoteText;
String newNoteId = DateTime.now().toIso8601String();
TextEditingController titleController = TextEditingController();
TextEditingController commentController = TextEditingController();
return SafeArea(
child: Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
centerTitle: true,
backgroundColor: Colors.black12,
title: Text(
'Add a note ',
style: TextStyle(
fontFamily: 'Volkhov',
color: Colors.white,
fontWeight: FontWeight.w400,
fontSize: 25.0),
textAlign: TextAlign.center,
),
),
backgroundColor: Color(0xff212121),
body: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
// SizedBox(
// height: 80,
// ),
Container(
width: 400,
height: 350,
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(20),
),
),
margin: EdgeInsets.fromLTRB(30, 20, 30, 20),
color: Colors.white12,
child: Column(
children: [
Padding(
padding: EdgeInsets.all(10),
child: TextField(
maxLength: 20,
maxLines: null,
textAlign: TextAlign.start,
decoration: InputDecoration(
prefixIcon: GestureDetector(
onTap: () {
showDatePicker(
context: context,
initialDate: daytime == null
? DateTime.now()
: daytime,
firstDate: DateTime(1970),
lastDate: DateTime(2100),
).then((date) {
setState(() {
daytime = date;
});
});
},
child: Icon(
Icons.date_range,
color: Colors.deepPurple,
),
),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.amber),
borderRadius: BorderRadius.all(
Radius.circular(10),
),
),
hintText:
'Enter title or press the icon to select a date',
hintStyle: TextStyle(color: Colors.white),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.deepPurple),
borderRadius: BorderRadius.all(
Radius.circular(10),
),
),
),
style: TextStyle(
fontSize: 11.0,
color: Colors.white,
// fontStyle: FontStyle.italic,
),
controller: titleController,
// onChanged: (newtitle) {
// newNoteText = newtitle;
// },
),
),
SizedBox(
height: 30,
),
Padding(
padding: EdgeInsets.all(10),
child: TextField(
maxLines: null,
maxLength: 500,
textAlign: TextAlign.start,
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.amber),
),
hintText: 'Comments',
hintStyle: TextStyle(color: Colors.grey),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.deepPurple),
),
),
style: TextStyle(
fontSize: 15.0,
color: Colors.white,
// fontStyle: FontStyle.italic,
),
controller: commentController,
// onChanged: (newText) {
// newNoteText = newText;
// },
),
),
],
),
),
),
SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
RaisedButton(
elevation: 20,
onPressed: () {
Navigator.pop(context);
},
color: Colors.amber,
child: Icon(
Icons.arrow_back,
color: Colors.black,
),
),
SizedBox(
width: 20,
),
RaisedButton(
elevation: 25,
child: Text(
'Save',
style: TextStyle(color: Colors.black),
),
color: Colors.amber,
onPressed: () {
if (titleController.text.isEmpty && daytime == null) {
newNoteTitle = 'No title';
} else if (titleController.text.isEmpty &&
daytime != null) {
newNoteTitle = DateFormat('yyy/MM/dd').format(daytime);
} else if (titleController.text != null &&
daytime == null) {
newNoteTitle = titleController.text;
} else {
newNoteTitle = titleController.text +
' - ' +
DateFormat('yyy/MM/dd').format(daytime);
}
commentController.text.isEmpty
? newNoteText = 'No comments'
: newNoteText = commentController.text;
// Provider.of<Notes>(context, listen: false).addNote(
DBHelper.insert(
'user_notes',
{
'title': newNoteTitle,
'text': newNoteText,
'id': newNoteId
},
);
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => MainScreen()),
);
},
),
],
)
],
),
),
),
);
}
}
I understand i do something wrong when i set the State on the datepicker...also for the bad code...

Please check this code. You are using same textfield for both work, better you use different textfield.
TextField(
maxLength: 20,
maxLines: null,
textAlign: TextAlign.start,
decoration: InputDecoration(
prefixIcon: GestureDetector(
onTap: () {
showDatePicker(
context: context,
initialDate: daytime == null ? DateTime.now() : daytime,
firstDate: DateTime(1970),
lastDate: DateTime(2100),
).then((date) {
setState(() {
daytime = date;
titleController.text =
daytime.toString() + titleController.text;
});
});
},
child: Icon(
Icons.date_range,
color: Colors.deepPurple,
),
),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.amber),
borderRadius: BorderRadius.all(
Radius.circular(10),
),
),
hintText: 'Enter title or press the icon to select a date',
hintStyle: TextStyle(color: Colors.red),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.deepPurple),
borderRadius: BorderRadius.all(
Radius.circular(10),
),
),
),
style: TextStyle(
fontSize: 11.0,
color: Colors.red,
// fontStyle: FontStyle.italic,
),
controller: titleController,
)

Not sure what exactly wrong you are doing in the code, but you can set text externally for that maintain the variable and assign value to titleController.text
setState(() {
daytime = date;
titleController.text = 'Text Message';
});

I am using the controllers in this way, Try out below
final titleController = TextEditingController();
final commentController = TextEditingController();

Try to define your controller out of widget build because when setState works it keeps rebuilding your controller.
TextEditingController titleController = TextEditingController();
TextEditingController commentController = TextEditingController();
Widget build(BuildContext context) {}

Related

Could not find a generator for route RouteSettings("/sendotp", null) in the _WidgetsAppState

I want to navigate from one page to another on flutter but i am getting this error what to do The code Is given below
Route.dart
class MyRoute{
static String loginroute = "/login" ;
static String homeroute = "/homepage";
static String registeroute = "/register";
static String ourserviceroute = "/ourservice";
static String aboutusroute = "/about";
static String contactusroute = "/contact";
static String settingspageroute = "/setting";
static String sendotproute = "/sendotp";
}
The register.dart is
import 'package:app_first/utilities/route.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class RegisterPage extends StatefulWidget {
const RegisterPage({super.key});
#override
State<RegisterPage> createState() => _RegisterPageState();
}
class _RegisterPageState extends State<RegisterPage> {
bool isloading = false;
final _formkey=GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Center(child: Text("FOODIES#CU"),)
),
body: Center(
child: Padding(
padding:
const EdgeInsets.symmetric(vertical: 130, horizontal: 40),
child: SingleChildScrollView(
child: Form(
key: _formkey,
child: Column(
children: [
TextFormField(
decoration: InputDecoration(
hintText: ("Enter your name"),
labelText: ("Name"),
/* border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25),
borderSide: const BorderSide(
width: 0,
style: BorderStyle.solid,
)
),*/
),
validator: (value) {
if (value!.isEmpty) {
return "NAME CANNOT BE EMPTY";
}
return null;
},
),
SizedBox(
height: 15,
),
TextFormField(
decoration: InputDecoration(
hintText: ("Enter your username"),
labelText: ("Username"),
/*border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25),
borderSide: const BorderSide(
width: 0,
style: BorderStyle.solid,
)
),*/
),
validator: (value) {
if(value!.isEmpty)
{
return "USERNAME CANNOT BE EMPTY";
}
return null;
},
),
SizedBox(
height: 15,
),
TextFormField(
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly,
],
decoration: InputDecoration(
hintText: ("Enter your mobile no."),
labelText: ("Mobile no."),
/*border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25),
borderSide: const BorderSide(
width: 0,
style: BorderStyle.solid,
)
),*/
),
validator: (value) {
if(value!.isEmpty){
return "MOBILE NO. CANNOT BE EMPTY";
}
else if(value.length<=10){
return "MOBILE NUMBER MUST BE OF 10 DIGITS";
}
return null;
},
),
SizedBox(
height: 15,
),
TextFormField(
decoration: InputDecoration(
hintText: ("Enter your email "),
labelText: ("Email"),
suffixIcon: TextButton(
onPressed: (){
Navigator.pushNamed(context, MyRoute.sendotproute);
},
child: Text("Send otp"))
/* border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25),
borderSide: const BorderSide(
width: 0,
style: BorderStyle.solid,
)
),*/
),
validator: (value) {
if(value!.isEmpty)
{
return "EMAIL CANNOT BE EMPTY";
}
return null;
},
),
SizedBox(
height: 15,
),
TextFormField(
obscureText: true,
decoration: InputDecoration(
hintText: ("Enter your password"),
labelText: ("Password"),
/*border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25),
borderSide: const BorderSide(
width: 0,
style: BorderStyle.solid,
)
),*/
),
validator: (password) {
if(password!.isEmpty){
return "PASSWORD CANNOT BE EMPTY";
}
else if(password.length<8){
return "PASSWORD MUST BE ATLEAST 8 DIGITS";
}
return null;
},
),
SizedBox(
height: 15,
),
TextFormField(
obscureText: true,
decoration: InputDecoration(
hintText: ("Enter confirm password"),
labelText: ("Confirm Password"),
/* border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25),
borderSide: const BorderSide(
width: 0,
style: BorderStyle.solid,
)
),*/
),
validator: (value) {
if(value!.isEmpty){
return "CONFIRM PASSWORD CANNOT BE EMPTY";
}
else if(value.length<8){
return "CONFIRM PASSWORD MUST BE ATLEAST 8 DIGITS";
}
return null;
},
),
SizedBox(height: 30,),
Material(
borderRadius: BorderRadius.circular(6),
color: Colors.blueGrey,
child: InkWell(
onTap: ()async
{
if(_formkey.currentState!.validate()){
setState(() {
isloading=true;
});
setState(() {
isloading = true;
});
await Future.delayed(Duration(seconds: 1));
Navigator.pushNamed(context, MyRoute.loginroute);
setState(() {
isloading=false;
});
}
},
child: AnimatedContainer(
duration: Duration(seconds: 1),
width: 140,
height: 40,
//color: Colors.blueGrey,
alignment: Alignment.center,
child: Text("Register now",
style: TextStyle(
//fontWeight: FontWeight.bold,
color: Colors.white,
),
),
/*decoration: BoxDecoration(
borderRadius: BorderRadius.circular(6),
color: Colors.blueGrey,*/
),
),
),
],
),
),
),
)
),
);
}
}
And the drawer.dart is
import 'package:app_first/utilities/route.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:eva_icons_flutter/eva_icons_flutter.dart';
class MyDrawer extends StatelessWidget {
const MyDrawer({super.key});
#override
Widget build(BuildContext context) {
Image.asset("assets/images/profile.png");
return Drawer(
backgroundColor: Colors.white,
child: ListView(
children: [
DrawerHeader(
padding: EdgeInsets.zero,
child: UserAccountsDrawerHeader(
accountEmail: Text("Kushagrasinha11111#gmail.com"),
accountName: Text("Kushagra Sinha"),
currentAccountPicture: CircleAvatar(
backgroundImage: AssetImage("assets/images/profile.png"),
)
),
),
ListTile(
leading: Icon(
EvaIcons.homeOutline, color: Color.fromARGB(255, 38, 4, 229),),
title: Text("Home", style:
TextStyle(
fontWeight: FontWeight.bold,
color: Colors.black,
fontSize: 20,
),),
onTap: () {
Navigator.pushNamed(context, MyRoute.homeroute);
},
),
SizedBox(
height: 3,
),
ListTile(
leading: Icon(
EvaIcons.shoppingCartOutline, color: Color.fromARGB(255, 38, 4, 229),),
title: Text("Our services", style:
TextStyle(
fontWeight: FontWeight.bold,
color: Colors.black,
fontSize: 20,
),),
onTap: () {
Navigator.pushNamed(context, MyRoute.ourserviceroute);
},
),
SizedBox(
height: 3,
),
ListTile(
leading: Icon(
EvaIcons.bookOpenOutline, color: Color.fromARGB(255, 38, 4, 229),),
title: Text("About us", style:
TextStyle(
fontWeight: FontWeight.bold,
color: Colors.black,
fontSize: 20,
),),
onTap: () {
Navigator.pushNamed(context, MyRoute.aboutusroute);
},
),
SizedBox(
height: 3,
),
ListTile(
leading: Icon(
EvaIcons.phoneCallOutline, color: Color.fromARGB(255, 38, 4, 229),),
title: Text("Contact us", style:
TextStyle(
fontWeight: FontWeight.bold,
color: Colors.black,
fontSize: 20,
),),
onTap: () {
Navigator.pushNamed(context, MyRoute.contactusroute);
},
),
SizedBox(
height: 3,
),
ListTile(
leading: Icon(
EvaIcons.settings2Outline, color: Color.fromARGB(255, 38, 4, 229),),
title: Text("Settings", style:
TextStyle(
fontWeight: FontWeight.bold,
color: Colors.black,
fontSize: 20,
),),
onTap: () {
Navigator.pushNamed(context, MyRoute.settingspageroute);
},
),
SizedBox(
height: 3,
),
ListTile(
leading: Icon(
EvaIcons.logOutOutline, color: Color.fromARGB(255, 38, 4, 229),),
title: Text("Log out", style:
TextStyle(
fontWeight: FontWeight.bold,
color: Colors.black,
fontSize: 20,
),),
onTap: () {
Navigator.pushNamed(context, MyRoute.loginroute);
},
),
],
),
);
}
}
I am getting the error could not find generator help me with this
I am getting the error could not find the generator help me please

SingleChildScrollView isn't working in my login screen

this is the login screen I had Implemented using flutter. I want this screen to be scrollable. how can I do that? I have uploaded my login screen code for your reference. I have tried out my column wrap with a single-child scroll view. but it doesn't work. there are multiple columns, maybe I'm wrapping the wrong column. I appriciate your help on this.
class LoginScreen extends StatefulWidget {
const LoginScreen({Key? key}) : super(key: key);
#override
_LoginScreenState createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
#override
Widget build(BuildContext context) {
final Size = MediaQuery.of(context).size;
return GestureDetector(
onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
child: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [Color.fromARGB(255, 3, 86, 124), Color(0xff141a3a)],
begin: Alignment.topRight,
end: Alignment.bottomLeft,
)),
child: Scaffold(
backgroundColor: Colors.transparent,
resizeToAvoidBottomInset: false,
body: Padding(
padding: const EdgeInsets.only(top: 40, left: 20, right: 20),
child: Column(
children: [
Expanded(
flex: 2,
child: Column(
children: [
// Spacer(flex: 1),
Image(
image: const AssetImage(
'assets/images/LogoVector.png',
),
height: Size.width / 2.9,
width: Size.width / 2.9,
),
SizedBox(height: 5),
Text(
"LOGIN",
textAlign: TextAlign.left,
style: TextStyle(
fontSize: 30,
color: textWhite,
fontFamily: "Roboto"),
),
],
),
),
// const Spacer(flex: 1),
const Expanded(flex: 3, child: Center(child: LoginForm())),
],
),
),
),
),
);
}
}
class LoginForm extends StatefulWidget {
const LoginForm({Key? key}) : super(key: key);
#override
_LoginFormState createState() => _LoginFormState();
}
Map<String, String> loginUserData = {
'email': '',
'password': '',
'id': '',
'userName': '',
'token': '',
'userStatus': '',
};
class _LoginFormState extends State<LoginForm> {
TextEditingController emailEditingController = new TextEditingController();
TextEditingController passwordEditingController = new TextEditingController();
final _formKey = GlobalKey<FormState>();
String email = "";
String password = "";
String username = "";
bool isLoading = false;
bool typing = true;
bool _isObscure = true;
#override
Widget build(BuildContext context) {
final Size = MediaQuery.of(context).size;
return Form(
key: _formKey,
autovalidateMode: AutovalidateMode.disabled,
child: Column(
children: [
TextFormField(
controller: emailEditingController,
enabled: true,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30.0),
borderSide: const BorderSide(
color: textWhite,
),
// borderSide: BorderSide.none
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30.0),
borderSide: const BorderSide(color: textWhite),
),
errorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30.0),
borderSide: const BorderSide(color: Colors.red),
),
focusedErrorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30.0),
borderSide: const BorderSide(color: Colors.red),
),
isDense: true,
contentPadding: EdgeInsets.fromLTRB(10, 30, 10, 0),
hintText: "Email/ Username",
hintStyle: TextStyle(
color: textWhite, fontFamily: "Roboto", fontSize: 14),
),
style: TextStyle(color: textWhite),
validator: (String? UserName) {
if (UserName != null && UserName.isEmpty) {
return "Email can't be empty";
}
return null;
},
onChanged: (String? text) {
email = text!;
// print(email);
},
onSaved: (value) {
loginUserData['email'] = value!;
},
),
SizedBox(
height: 10,
),
TextFormField(
controller: passwordEditingController,
obscureText: _isObscure,
enabled: true,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30.0),
borderSide: const BorderSide(color: textWhite),
// borderSide: BorderSide.none
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30.0),
borderSide: const BorderSide(color: textWhite),
),
errorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
borderSide: const BorderSide(color: Colors.red),
),
focusedErrorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
borderSide: const BorderSide(color: Colors.red),
),
isDense: true,
contentPadding: EdgeInsets.fromLTRB(10, 10, 10, 0),
suffixIcon: IconButton(
icon: Icon(
_isObscure ? Icons.visibility : Icons.visibility_off),
color: textWhite,
onPressed: () {
setState(() {
_isObscure = !_isObscure;
});
}),
hintText: "Password",
hintStyle: TextStyle(
color: textWhite,
fontFamily: "Roboto",
fontSize: 14,
)),
style: TextStyle(color: textWhite),
validator: (String? Password) {
if (Password != null && Password.isEmpty) {
return "Password can't be empty";
}
return null;
},
onChanged: (String? text) {
password = text!;
print(password);
},
onSaved: (value) {
loginUserData['password'] = value!;
},
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Expanded(
child: CheckboxListTile(
title: const Text(
"Remember Me",
style: TextStyle(
color: textWhite, fontFamily: "Roboto", fontSize: 14),
),
activeColor: buttontext,
// tileColor: buttontext,
value: checkedValue,
onChanged: (newValue) {
FocusManager.instance.primaryFocus?.unfocus();
setState(() {
if (isLoading != true) {
checkedValue = newValue!;
print(newValue);
}
});
},
contentPadding: EdgeInsets.only(left: 0, top: 0),
controlAffinity:
ListTileControlAffinity.leading, // <-- leading Checkbox
),
),
TextButton(
child: Text(
"Forget Password",
style: TextStyle(
color: textWhite, fontFamily: "Roboto", fontSize: 14),
),
onPressed: () {
Get.to(() => Forget_Screen());
},
)
],
),
SizedBox(height: 40),
isLoading
? SpinKitDualRing(
color: textWhite,
size: 40,
)
: GestureDetector(
child: MainButton("Login"),
onTap: () async {
FocusManager.instance.primaryFocus?.unfocus();
if (_formKey.currentState!.validate()) {
_formKey.currentState!.save();
await LoginData();
// Get.to(BottomNavigation());
}
},
),
SizedBox(height: 15),
Container(
width: 275.0,
height: 40.0,
child: OutlinedButton(
onPressed: () {
Get.to(() => const Signup_Screen());
},
child: const Text(
'Signup',
style: TextStyle(
fontSize: 15, fontFamily: "Roboto", color: textWhite
//fontWeight: FontWeight.w500,
// color: Colors.black,
),
),
style: OutlinedButton.styleFrom(
side: const BorderSide(
width: 1.0,
color: textWhite,
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18.0),
),
),
),
)
],
),
);
}
}
You should wrap everything under the Scaffold:
Scaffold(
backgroundColor: Colors.transparent,
resizeToAvoidBottomInset: false,
body: SingleChildScrollView(child: Padding(
padding: const EdgeInsets.only(top: 40, left: 20, right: 20),
child: Column(
........
I can not see you using the SingleChildScrollView in then code sample you have provided with.
But if you want to make the page scrollable, Wrap the child of the scaffold in the SingleChildScrollView
Scaffold(
body: SingleChildScrollView(
....

How to write a code for update logged in user data into firebase using flutter

I'm a newbie for flutter and currently learning it by developing a small system for my university project. Below are my user register and profile view which I referenced from YouTube. But I do not know how to write a code for edit and delete the logged in user data (the personal information such as name and address)...
class RegMuser extends StatefulWidget {
const RegMuser({Key? key}) : super(key: key);
#override
_RegMuserState createState() => _RegMuserState();
}
class _RegMuserState extends State<RegMuser> {
bool hidePassword = true;
final formkey = GlobalKey<FormState>();
final nameEC = new TextEditingController();
final emailEC = new TextEditingController();
final nricEC = new TextEditingController();
final passwordEC = new TextEditingController();
final confirmPasswordEC = new TextEditingController();
final _auth = FirebaseAuth.instance;
#override
Widget build(BuildContext context) {
final nameField = TextFormField(
autofocus: false,
controller: nameEC,
keyboardType: TextInputType.name,
validator: (value) {
RegExp regex = new RegExp(r'^.{3,}$');
if (value!.isEmpty) {
return ("Name Cannot Be Empty");
}
if (!regex.hasMatch(value)) {
return ("Enter A Valid Name");
}
return null;
},
onSaved: (value) {
nameEC.text = value!;
},
textInputAction: TextInputAction.next,
decoration: InputDecoration(
prefixIcon: Icon(Icons.person),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
labelText: 'Name',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
);
final emailField = TextFormField(
autofocus: false,
controller: emailEC,
keyboardType: TextInputType.emailAddress,
validator: (value) {
if (value!.isEmpty) {
return ("Please Enter Your Email");
}
if (!RegExp("^[a-zA-Z0-9+_.-]+#[a-zA-Z0-9.-]+[a-z]").hasMatch(value)) {
return ("Please Enter Valid Email");
}
return null;
},
onSaved: (value) {
nameEC.text = value!;
},
textInputAction: TextInputAction.next,
decoration: InputDecoration(
prefixIcon: Icon(Icons.mail),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
labelText: "Email",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
);
final nricField = TextFormField(
autofocus: false,
controller: nricEC,
keyboardType: TextInputType.number,
validator: (value) {
RegExp regex = new RegExp(r'[0-9]');
if (value!.isEmpty) {
return ("NRIC Cannot Be Empty");
}
if (!regex.hasMatch(value)) {
return ("Enter A Valid NRIC");
}
if (nricEC.text.length != 12) {
return ("Enter A Valid NRIC");
}
return null;
},
onSaved: (value) {
nricEC.text = value!;
},
textInputAction: TextInputAction.next,
decoration: InputDecoration(
prefixIcon: Icon(Icons.card_membership),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
labelText: "NRIC",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
);
final passwordField = TextFormField(
autofocus: false,
controller: passwordEC,
obscureText: hidePassword,
validator: (value) {
RegExp regex = new RegExp(r'^.{6,}$');
if (value!.isEmpty) {
return ("Password Is Required For Login");
}
if (!regex.hasMatch(value)) {
return ("Please Enter Valid Password");
}
},
textInputAction: TextInputAction.next,
decoration: InputDecoration(
prefixIcon: Icon(Icons.vpn_key),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
labelText: "Pasword",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
suffixIcon: InkWell(
onTap: togglePasswordView,
child: Icon(
Icons.visibility,
),
),
),
);
final confirmPasswordField = TextFormField(
autofocus: false,
controller: confirmPasswordEC,
obscureText: hidePassword,
validator: (value) {
if (confirmPasswordEC.text != passwordEC.text) {
return "Password Don't Match";
}
return null;
},
textInputAction: TextInputAction.next,
decoration: InputDecoration(
prefixIcon: Icon(Icons.vpn_key),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
labelText: "Confirm Pasword",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
suffixIcon: InkWell(
onTap: togglePasswordView,
child: Icon(
Icons.visibility,
),
),
),
);
final signUpButton = Material(
elevation: 5,
borderRadius: BorderRadius.circular(30),
color: Colors.blue[400],
child: MaterialButton(
padding: EdgeInsets.fromLTRB(20, 15, 20, 15),
minWidth: MediaQuery.of(context).size.width,
onPressed: () {
signUp(emailEC.text, passwordEC.text);
},
child: Text(
"Sign Up",
style: TextStyle(
fontSize: 20,
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
),
);
return Scaffold(
backgroundColor: Colors.blueGrey[100],
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
leading: IconButton(
icon: Icon(
Icons.arrow_back,
color: Colors.black,
),
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: 20),
nameField,
SizedBox(height: 20),
emailField,
SizedBox(height: 20),
nricField,
SizedBox(height: 20),
passwordField,
SizedBox(height: 20),
confirmPasswordField,
SizedBox(height: 20),
signUpButton,
SizedBox(height: 10),
],
),
),
),
),
),
),
);
}
void togglePasswordView() {
setState(() {
hidePassword = !hidePassword;
});
}
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 {
FirebaseFirestore firebaseFirestore = FirebaseFirestore.instance;
User? mUser = _auth.currentUser;
Muser muser = Muser();
muser.email = mUser!.email;
muser.uid = mUser.uid;
muser.name = nameEC.text;
muser.nric = nricEC.text;
await firebaseFirestore
.collection("mUsers")
.doc(muser.uid)
.set(muser.toMap());
Fluttertoast.showToast(msg: "Account Created Successfully");
Navigator.pushAndRemoveUntil((context),
MaterialPageRoute(builder: (context) => homePage()), (route) => false);
}
}
Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
child: Container(
child: Column(
children: <Widget>[
ListTile(
title: Text(
"Name",
style: TextStyle(
color: Colors.black54,
fontSize: 13,
fontWeight: FontWeight.bold,
),
),
subtitle: Text(
"${loggedInUser.name}",
style: TextStyle(
color: Colors.black,
fontSize: 18,
),
),
shape: RoundedRectangleBorder(
side: BorderSide(
color: Colors.black54,
width: 3,
),
borderRadius: BorderRadius.circular(10),
),
),
SizedBox(height: 10.0),
ListTile(
title: Text(
"Email",
style: TextStyle(
color: Colors.black54,
fontSize: 13,
fontWeight: FontWeight.bold,
),
),
subtitle: Text(
"${loggedInUser.email}",
style: TextStyle(
color: Colors.black,
fontSize: 18,
),
),
shape: RoundedRectangleBorder(
side: BorderSide(
color: Colors.black54,
width: 3,
),
borderRadius: BorderRadius.circular(10),
),
),
SizedBox(height: 10.0),
ListTile(
title: Text(
"Position",
style: TextStyle(
color: Colors.black54,
fontSize: 13,
fontWeight: FontWeight.bold,
),
),
subtitle: Text(
"${loggedInUser.post}",
style: TextStyle(
color: Colors.black,
fontSize: 18,
),
),
shape: RoundedRectangleBorder(
side: BorderSide(
color: Colors.black54,
width: 3,
),
borderRadius: BorderRadius.circular(10),
),
),
SizedBox(height: 10.0),
ListTile(
title: Text(
"Department",
style: TextStyle(
color: Colors.black54,
fontSize: 13,
fontWeight: FontWeight.bold,
),
),
subtitle: Text(
"${loggedInUser.dept}",
style: TextStyle(
color: Colors.black,
fontSize: 18,
),
),
shape: RoundedRectangleBorder(
side: BorderSide(
color: Colors.black54,
width: 3,
),
borderRadius: BorderRadius.circular(10),
),
),
SizedBox(height: 10.0),
ListTile(
title: Text(
"Hospital",
style: TextStyle(
color: Colors.black54,
fontSize: 13,
fontWeight: FontWeight.bold,
),
),
subtitle: Text(
"${loggedInUser.hosp}",
style: TextStyle(
color: Colors.black,
fontSize: 18,
),
),
shape: RoundedRectangleBorder(
side: BorderSide(
color: Colors.black54,
width: 3,
),
borderRadius: BorderRadius.circular(10),
),
),
SizedBox(height: 10.0),
ListTile(
title: Text(
"Address",
style: TextStyle(
color: Colors.black54,
fontSize: 13,
fontWeight: FontWeight.bold,
),
),
subtitle: Text(
"${loggedInUser.street} ${loggedInUser.city} ${loggedInUser.postcode} ${loggedInUser.state} ${loggedInUser.country}",
style: TextStyle(
color: Colors.black,
fontSize: 18,
),
),
shape: RoundedRectangleBorder(
side: BorderSide(
color: Colors.black54,
width: 3,
),
borderRadius: BorderRadius.circular(10),
),
),
],
),
),
),
// Import the Firebase package
import 'package:firebase_auth/firebase_auth.dart';
// Create an instance of the Firebase authentication
final FirebaseAuth _auth = FirebaseAuth.instance;
// Create a function to update logged in user data
Future<void> updateUserData(String name, String email, String phone) async {
// Get the current logged in user
FirebaseUser user = await _auth.currentUser();
// Create a user update profile
UserUpdateInfo userInfo = UserUpdateInfo();
// Update the user profile with the provided data
userInfo.displayName = name;
userInfo.email = email;
userInfo.phoneNumber = phone;
// Finally update the user profile
await user.updateProfile(userInfo);
}

Flutter Problem: How to navigate to another page

I have a problem,My page is not going to homepage when i login,But why I dont know.
And the data is probably not coming in the submit fuction, then maybe that's why the login is not being done and I do not understand how the login will happen.
This is my auth.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:login_and_signup/Utils/api.dart';
import 'package:login_and_signup/Utils/http_exception.dart';
class Auth with ChangeNotifier {
var MainUrl = Api.authUrl;
Future<void> Authentication(String user_name, String user_email,
String mobile_no, String password, String action) async {
try {
// var url = Uri.parse('${MainUrl}/accounts:${endpoint}?key=${AuthKey}');
var url = Uri.parse('$MainUrl&action=$action');
print(url);
if (action == 'registration') {
final responce = await http.post(url, headers: {
"Accept": "Application/json"
}, body: {
"user_name": user_name,
'user_email': user_email,
"mobile_no": mobile_no,
"password": password,
});
print("Response" + responce.body);
final responceData = json.decode(responce.body);
print("responceData" + responceData);
} else {
final responce = await http.post(url, headers: {
"Accept": "Application/json"
}, body: {
"user_name": user_name,
'user_email': user_email,
"username": mobile_no,
"password": password,
});
print("Response" + responce.body);
final responceData = json.decode(responce.body);
print("responceData" + responceData);
}
} catch (e) {
throw e;
}
}
Future<void> login(
String user_name, String user_email, String mobile_no, String password) {
return Authentication(user_name, user_email, mobile_no, password, 'login');
}
Future<void> signUp(
String user_name, String user_email, String mobile_no, String password) {
return Authentication(
user_name, user_email, mobile_no, password, 'registration');
}
}
This is my login.dart
import 'package:flutter/material.dart';
import 'package:login_and_signup/Providers/auth.dart';
import 'package:login_and_signup/Screens/home_screen.dart';
// import 'package:login_and_signup/Providers/login_auth.dart';
import 'package:login_and_signup/Screens/signup.dart';
import 'package:login_and_signup/Utils/http_exception.dart';
import 'package:provider/provider.dart';
class LoginScreen extends StatefulWidget {
// static const String routeName = "/login";
#override
_LoginScreenState createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
final GlobalKey<FormState> _formKey = GlobalKey();
TextEditingController _mobileController = new TextEditingController();
TextEditingController _passwordController = new TextEditingController();
Map<String, String> _authData = {
'user_name': '',
'user_email': '',
'username': '',
'password': ''
};
Future _submit() async {
print('aa' + _authData['user_name']!);
if (!_formKey.currentState!.validate()) {
//invalid
return;
}
_formKey.currentState!.save();
try {
await Provider.of<Auth>(context, listen: false).login(
_authData['user_name']!,
_authData['user_email']!,
_authData['username']!,
_authData['password']!) .then((_) {
Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => HomePage()));
});;
print('aaaa');
} catch (e) {
}
}
#override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
// backgroundColor: Colors.white,
body: SingleChildScrollView(
child: Container(
child: Stack(
children: <Widget>[
Container(
height: MediaQuery.of(context).size.height * 0.65,
width: MediaQuery.of(context).size.width * 0.85,
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
topRight: Radius.circular(360),
bottomRight: Radius.circular(360)),
color: Colors.blue),
),
Container(
padding:
EdgeInsets.only(top: 50, left: 20, right: 20, bottom: 50),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Sign In",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 40),
),
SizedBox(
height: 10,
),
Text(
"Sign in with your username or email",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 10),
),
Form(
key: _formKey,
child: Container(
padding: EdgeInsets.only(top: 50, left: 20, right: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"username",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 12),
),
TextFormField(
// obscureText: true,
controller: _mobileController,
style: TextStyle(color: Colors.white),
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white),
),
prefixIcon: Icon(
Icons.vpn_key,
color: Colors.white,
)),
validator: (value) {
if (value!.isEmpty || value.length < 1) {
return 'valid no';
}
},
onSaved: (value) {
_authData['username'] = value!;
},
),
SizedBox(
height: 10,
),
SizedBox(
height: 10,
),
Text(
"Password",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 12),
),
TextFormField(
controller: _passwordController,
obscureText: true,
style: TextStyle(color: Colors.white),
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white),
),
prefixIcon: Icon(
Icons.vpn_key,
color: Colors.white,
)),
validator: (value) {
if (value!.isEmpty || value.length < 5) {
return 'Password is to Short';
}
},
onSaved: (value) {
_authData['password'] = value!;
},
),
Container(
padding: EdgeInsets.only(top: 40),
width: 140,
child: RaisedButton(
onPressed: () {
print(_authData['username']);
print(_authData['password']);
_submit();
},
shape: RoundedRectangleBorder(
borderRadius:
new BorderRadius.circular(10.0),
),
child: Text(
'Sign In',
style: TextStyle(color: Colors.white),
),
color: Colors.green),
),
Align(
alignment: Alignment.bottomRight,
child: InkWell(
onTap: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (ctx) => SignUpScreen()));
},
child: Container(
padding: EdgeInsets.only(top: 90),
child: Text(
"Create Account",
style: TextStyle(
decoration: TextDecoration.underline,
color: Colors.blue,
fontSize: 16),
),
),
),
)
],
),
),
),
],
),
),
],
),
),
),
);
}
void _showerrorDialog(String message) {
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: Text(
'An Error Occurs',
style: TextStyle(color: Colors.blue),
),
content: Text(message),
actions: <Widget>[
FlatButton(
child: Text('Okay'),
onPressed: () {
Navigator.of(context).pop();
},
)
],
),
);
}
}
This is my signup.dart
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:login_and_signup/Providers/auth.dart';
import 'package:login_and_signup/Providers/signup_auth.dart';
// import 'package:login_and_signup/Providers/signup_auth.dart';
import 'package:login_and_signup/Screens/home_screen.dart';
import 'package:login_and_signup/Screens/login.dart';
import 'package:login_and_signup/Utils/http_exception.dart';
import 'package:provider/provider.dart';
class SignUpScreen extends StatefulWidget {
#override
_SignUpScreenState createState() => _SignUpScreenState();
}
class _SignUpScreenState extends State<SignUpScreen> {
final GlobalKey<FormState> _formKey = GlobalKey();
Map<String, String> _authData = {
'user_name': '',
'user_email': '',
'mobile_no': '',
'password': '',
};
TextEditingController _nameController = new TextEditingController();
TextEditingController _emailController = new TextEditingController();
TextEditingController _mobileController = new TextEditingController();
TextEditingController _passwordController = new TextEditingController();
Future _submit() async {
if (!_formKey.currentState!.validate()) {
//invalid
return;
}
_formKey.currentState!.save();
try {
await Provider.of<Auth>(context, listen: false).signUp(
_authData['user_name']!,
_authData['user_email']!,
_authData['mobile_no']!,
_authData['password']!) .then((_) {
Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => HomePage()));
});; } catch (e) {
}
}
#override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
// backgroundColor: Colors.white,
body: SingleChildScrollView(
child: Container(
child: Stack(
children: <Widget>[
Container(
height: MediaQuery.of(context).size.height * 0.65,
width: MediaQuery.of(context).size.width * 0.85,
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
topRight: Radius.circular(360),
bottomRight: Radius.circular(360)),
color: Colors.blue),
),
Container(
padding:
EdgeInsets.only(top: 50, left: 20, right: 20, bottom: 50),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Sign Up",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 40),
),
SizedBox(
height: 10,
),
Text(
"Sign up with username or email",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 10),
),
Form(
key: _formKey,
child: Container(
padding: EdgeInsets.only(top: 50, left: 20, right: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"name",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 12),
),
TextFormField(
// obscureText: true,
controller: _nameController,
style: TextStyle(color: Colors.white),
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white),
),
prefixIcon: Icon(
Icons.person,
color: Colors.white,
)),
validator: (value) {
if (value!.isEmpty) {
return 'Please Enter name';
}
},
onSaved: (value) {
_authData['user_name'] = value!;
},
),
SizedBox(
height: 10,
),
Text(
" Email",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 12),
),
TextFormField(
controller: _emailController,
style: TextStyle(color: Colors.white),
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white),
),
prefixIcon: Icon(
Icons.person,
color: Colors.white,
)),
validator: (value) {
if (value!.isEmpty || !value.contains('#')) {
return 'Invalid email';
}
},
onSaved: (value) {
_authData['user_email'] = value!;
},
),
SizedBox(
height: 10,
),
Text(
"mobile",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 12),
),
TextFormField(
// obscureText: true,
controller: _mobileController,
style: TextStyle(color: Colors.white),
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white),
),
prefixIcon: Icon(
Icons.vpn_key,
color: Colors.white,
)),
validator: (value) {
if (value!.isEmpty || value.length < 10) {
return 'valid no';
}
},
onSaved: (value) {
_authData['mobile_no'] = value!;
},
),
SizedBox(
height: 10,
),
Text(
"Password",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 12),
),
TextFormField(
obscureText: true,
controller: _passwordController,
style: TextStyle(color: Colors.white),
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white),
),
prefixIcon: Icon(
Icons.vpn_key,
color: Colors.white,
)),
validator: (value) {
if (value!.isEmpty || value.length < 5) {
return 'Password is to Short';
}
},
onSaved: (value) {
_authData['password'] = value!;
},
),
SizedBox(
height: 10,
),
Text(
"Confirm Password",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 12),
),
TextFormField(
obscureText: true,
style: TextStyle(color: Colors.white),
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white),
),
prefixIcon: Icon(
Icons.vpn_key,
color: Colors.white,
)),
validator: (value) {
if (value != _passwordController.text) {
return 'Password doesnot match';
}
},
),
Container(
padding: EdgeInsets.only(top: 40),
width: 140,
child: RaisedButton(
onPressed: () {
print(_authData['mobile_no']);
print(_authData['password']);
_submit();
},
shape: RoundedRectangleBorder(
borderRadius:
new BorderRadius.circular(10.0),
),
child: Text(
'Sign Up',
style: TextStyle(color: Colors.white),
),
color: Colors.green),
),
Align(
alignment: Alignment.bottomRight,
child: InkWell(
onTap: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (ctx) => LoginScreen()));
},
child: Container(
padding: EdgeInsets.only(top: 90),
child: Text(
"Sign In",
style: TextStyle(
decoration: TextDecoration.underline,
color: Colors.blue,
fontSize: 16),
),
),
),
)
],
),
),
),
],
),
),
],
),
),
),
);
}
void _showerrorDialog(String message) {
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: Text(
'An Error Occurs',
style: TextStyle(color: Colors.blue),
),
content: Text(message),
actions: <Widget>[
FlatButton(
child: Text('Okay'),
onPressed: () {
Navigator.of(context).pop();
},
)
],
),
);
}
}
what error are you getting when you tap of login?You can try to use a route generator class
class RouteGenerator {
static Route<dynamic>? generateRoute(RouteSettings settings) {
// Getting arguments passed in while calling Navigator.pushNamed
final args = settings.arguments;
switch (settings.name) {
case '/'://this will the first page get loaded
return MaterialPageRoute(builder: (_) => LoginPage());
case '/home':
return MaterialPageRoute(builder: (_) => MyHomePage());
}
}
}
From the main.dart call the initial page as follows
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
initialRoute: '/',//
onGenerateRoute: RouteGenerator.generateRoute,
);
}
}
call the other pages as
Navigator.of(context)
.pushNamed('/home');

The method 'validate' was called on null

The Method validate is calling null
How can I fix it?
Here is my code
saveUserInfoToFireStore() async {
final GoogleSignInAccount gCurrentUser = gSignIn.currentUser;
DocumentSnapshot documentSnapshot =
await userRefrence.document(gCurrentUser.id).get();
if (!documentSnapshot.exists) {
final username = await Navigator.push(context,
MaterialPageRoute(builder: (context) => CreateAccountPage()));}
CreateAccountPage.dart
class _CreateAccountPageState extends State<CreateAccountPage> {
final _scaffoldKey = GlobalKey<ScaffoldState>();
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
// final _formKey = GlobalKey<FormState>();
String username;
submitUsername() {
final form = _formKey.currentState;
if (form.validate()) {
form.save();
SnackBar snackBar = SnackBar(
content: Text("Welcome" + username),
);
_scaffoldKey.currentState.showSnackBar(snackBar);
Timer(Duration(seconds: 4), () {
Navigator.pop(context, username);
});
}
}
#override
Widget build(BuildContext parentContext) {
return Scaffold(
key: _scaffoldKey,
appBar:
header(context, strTitle: "Settings", disappearedBackButton: true),
body: ListView(
children: <Widget>[
Container(
child: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 26.0),
child: Center(
child: Text(
"Set up a Username",
style: TextStyle(fontSize: 26.0),
),
),
),
Padding(
padding: EdgeInsets.all(17.0),
child: Container(
child: Form(
key: _formKey,
autovalidate: true,
child: TextFormField(
style: TextStyle(color: Colors.white),
validator: (val) {
if (val.trim().length < 5 || val.isEmpty) {
return "user name is very Short";
} else if (val.trim().length < 10 || val.isEmpty) {
return "user name is very long";
} else {
return null;
}
},
onSaved: (val) => username = val,
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.grey),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white),
),
border: OutlineInputBorder(),
labelText: "Username",
labelStyle: TextStyle(fontSize: 16.0),
hintText: "must be atleast 5 charecters",
hintStyle: TextStyle(color: Colors.grey),
),
),
),
),
),
GestureDetector(
onTap: submitUsername(),
child: Container(
height: 55.0,
width: 360.0,
decoration: BoxDecoration(
color: Colors.lightGreen,
borderRadius: BorderRadius.circular(8.0),
),
child: Center(
child: Text(
"Proceed",
style: TextStyle(
color: Colors.white,
fontSize: 16.0,
fontWeight: FontWeight.bold,
),
),
),
),
),
],
),
)
],
),
);
}
}
The issue was with your onTap function.
submitUsername inside onPressed is a function reference, which means it is not executed immediately. It is executed after the user clicks on the Button
While,
submitUsername() is a function call and it is executed immediately.
You should use submitUsername and not submitUsername().
GestureDetector(
onTap: submitUsername, //new line
child: Container(
height: 55.0,
width: 360.0,
decoration: BoxDecoration(
color: Colors.lightGreen,
borderRadius: BorderRadius.circular(8.0),
),
child: Center(
child: Text(
"Proceed",
style: TextStyle(
color: Colors.white,
fontSize: 16.0,
fontWeight: FontWeight.bold,
),
),
),
),
),
OR
Call the submitUsername function inside an anonymous function that will act as a callback.
GestureDetector(
onTap: (){
submitUsername();
},
child: Container(
height: 55.0,
width: 360.0,
decoration: BoxDecoration(
color: Colors.lightGreen,
borderRadius: BorderRadius.circular(8.0),
),
child: Center(
child: Text(
"Proceed",
style: TextStyle(
color: Colors.white,
fontSize: 16.0,
fontWeight: FontWeight.bold,
),
),
),
),
),