I'm new to flutter and I have created an application with login/signup screens and connected my app to fire base, it's successfully connected but when signup or login it keeps spinning. However, I can see in firebase user is added but it doesn't get access to application home screen.
Here is my dart code for sign up:
import 'dart:io';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_login_screen/model/User.dart';
import 'package:flutter_login_screen/ui/home/HomeScreen.dart';
import 'package:flutter_login_screen/ui/services/Authenticate.dart';
import 'package:flutter_login_screen/ui/utils/helper.dart';
import 'package:image_picker/image_picker.dart';
import '../../constants.dart' as Constants;
import '../../constants.dart';
import '../../main.dart';
File _image;
class SignUpScreen extends StatefulWidget {
#override
State createState() => _SignUpState();
}
class _SignUpState extends State<SignUpScreen> {
TextEditingController _passwordController = new TextEditingController();
GlobalKey<FormState> _key = new GlobalKey();
bool _validate = false;
String firstName, lastName, email, mobile, password, confirmPassword;
#override
Widget build(BuildContext context) {
if (Platform.isAndroid) {
retrieveLostData();
}
return Scaffold(
appBar: AppBar(
elevation: 0.0,
backgroundColor: Colors.transparent,
iconTheme: IconThemeData(color: Colors.black),
),
body: SingleChildScrollView(
child: new Container(
margin: new EdgeInsets.only(left: 16.0, right: 16, bottom: 16),
child: new Form(
key: _key,
autovalidate: _validate,
child: formUI(),
),
),
),
);
}
Future<void> retrieveLostData() async {
final LostDataResponse response = await ImagePicker.retrieveLostData();
if (response == null) {
return;
}
if (response.file != null) {
setState(() {
_image = response.file;
});
}
}
_onCameraClick() {
final action = CupertinoActionSheet(
message: Text(
"Add profile picture",
style: TextStyle(fontSize: 15.0),
),
actions: <Widget>[
CupertinoActionSheetAction(
child: Text("Choose from gallery"),
isDefaultAction: false,
onPressed: () async {
Navigator.pop(context);
var image =
await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
_image = image;
});
},
),
CupertinoActionSheetAction(
child: Text("Take a picture"),
isDestructiveAction: false,
onPressed: () async {
Navigator.pop(context);
var image = await ImagePicker.pickImage(source: ImageSource.camera);
setState(() {
_image = image;
});
},
)
],
cancelButton: CupertinoActionSheetAction(
child: Text("Cancel"),
onPressed: () {
Navigator.pop(context);
},
),
);
showCupertinoModalPopup(context: context, builder: (context) => action);
}
Widget formUI() {
return new Column(
children: <Widget>[
new Align(
alignment: Alignment.topLeft,
child: Text(
'Create new account',
style: TextStyle(
color: Colors.deepOrange[900],
fontWeight: FontWeight.bold,
fontSize: 25.0),
)),
Padding(
padding:
const EdgeInsets.only(left: 8.0, top: 32, right: 8, bottom: 8),
child: Stack(
alignment: Alignment.bottomCenter,
children: <Widget>[
CircleAvatar(
radius: 65,
backgroundColor: Colors.grey.shade400,
child: ClipOval(
child: SizedBox(
width: 170,
height: 170,
child: _image == null
? Image.asset(
'assets/images/placeholder.jpg',
fit: BoxFit.cover,
)
: Image.file(
_image,
fit: BoxFit.cover,
),
),
),
),
Positioned(
left: 80,
right: 0,
child: FloatingActionButton(
backgroundColor: Color(COLOR_ACCENT),
child: Icon(Icons.camera_alt),
mini: true,
onPressed: _onCameraClick),
)
],
),
),
ConstrainedBox(
constraints: BoxConstraints(minWidth: double.infinity),
child: Padding(
padding:
const EdgeInsets.only(top: 16.0, right: 8.0, left: 8.0),
child: TextFormField(
validator: validateName,
onSaved: (String val) {
firstName = val;
},
textInputAction: TextInputAction.next,
onFieldSubmitted: (_) => FocusScope.of(context).nextFocus(),
decoration: InputDecoration(
contentPadding: new EdgeInsets.symmetric(
vertical: 8, horizontal: 16),
fillColor: Colors.white,
hintText: 'First Name',
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: BorderSide(
color: Colors.deepOrange[900],
width: 2.0)),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
))))),
ConstrainedBox(
constraints: BoxConstraints(minWidth: double.infinity),
child: Padding(
padding:
const EdgeInsets.only(top: 16.0, right: 8.0, left: 8.0),
child: TextFormField(
validator: validateName,
onSaved: (String val) {
lastName = val;
},
textInputAction: TextInputAction.next,
onFieldSubmitted: (_) => FocusScope.of(context).nextFocus(),
decoration: InputDecoration(
contentPadding: new EdgeInsets.symmetric(
vertical: 8, horizontal: 16),
fillColor: Colors.white,
hintText: 'Last Name',
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: BorderSide(
color: Colors.deepOrange[900],
width: 2.0)),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
))))),
ConstrainedBox(
constraints: BoxConstraints(minWidth: double.infinity),
child: Padding(
padding:
const EdgeInsets.only(top: 16.0, right: 8.0, left: 8.0),
child: TextFormField(
keyboardType: TextInputType.phone,
textInputAction: TextInputAction.next,
onFieldSubmitted: (_) => FocusScope.of(context).nextFocus(),
validator: validateMobile,
onSaved: (String val) {
mobile = val;
},
decoration: InputDecoration(
contentPadding: new EdgeInsets.symmetric(
vertical: 8, horizontal: 16),
fillColor: Colors.white,
hintText: 'Mobile Number',
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: BorderSide(
color: Colors.deepOrange[900],
width: 2.0)),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
))))),
ConstrainedBox(
constraints: BoxConstraints(minWidth: double.infinity),
child: Padding(
padding:
const EdgeInsets.only(top: 16.0, right: 8.0, left: 8.0),
child: TextFormField(
keyboardType: TextInputType.emailAddress,
textInputAction: TextInputAction.next,
onFieldSubmitted: (_) => FocusScope.of(context).nextFocus(),
validator: validateEmail,
onSaved: (String val) {
email = val;
},
decoration: InputDecoration(
contentPadding: new EdgeInsets.symmetric(
vertical: 8, horizontal: 16),
fillColor: Colors.white,
hintText: 'Email Address',
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: BorderSide(
color: Colors.deepOrange[900],
width: 2.0)),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
))))),
ConstrainedBox(
constraints: BoxConstraints(minWidth: double.infinity),
child: Padding(
padding: const EdgeInsets.only(top: 16.0, right: 8.0, left: 8.0),
child: TextFormField(
obscureText: true,
textInputAction: TextInputAction.next,
onFieldSubmitted: (_) => FocusScope.of(context).nextFocus(),
controller: _passwordController,
validator: validatePassword,
onSaved: (String val) {
password = val;
},
style: TextStyle(height: 0.8, fontSize: 18.0),
cursorColor: Colors.deepOrange[900],
decoration: InputDecoration(
contentPadding:
new EdgeInsets.symmetric(vertical: 8, horizontal: 16),
fillColor: Colors.white,
hintText: 'Password',
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: BorderSide(
color: Colors.deepOrange[900],
width: 2.0)),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
))),
)),
ConstrainedBox(
constraints: BoxConstraints(minWidth: double.infinity),
child: Padding(
padding: const EdgeInsets.only(top: 16.0, right: 8.0, left: 8.0),
child: TextFormField(
textInputAction: TextInputAction.done,
onFieldSubmitted: (_) {
_sendToServer();
},
obscureText: true,
validator: (val) =>
validateConfirmPassword(_passwordController.text, val),
onSaved: (String val) {
confirmPassword = val;
},
style: TextStyle(height: 0.8, fontSize: 18.0),
cursorColor: Colors.deepOrange[900],
decoration: InputDecoration(
contentPadding:
new EdgeInsets.symmetric(vertical: 8, horizontal: 16),
fillColor: Colors.white,
hintText: 'Confirm Password',
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: BorderSide(
color: Colors.deepOrange[900], width: 2.0)),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
))),
),
),
Padding(
padding: const EdgeInsets.only(right: 40.0, left: 40.0, top: 40.0),
child: ConstrainedBox(
constraints: const BoxConstraints(minWidth: double.infinity),
child: RaisedButton(
color: Color(Constants.FACEBOOK_BUTTON_COLOR),
child: Text(
'Sign Up',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
textColor: Colors.white,
splashColor: Color(Constants.FACEBOOK_BUTTON_COLOR),
onPressed: _sendToServer,
padding: EdgeInsets.only(top: 12, bottom: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(25.0),
side: BorderSide(
color: Color(Constants.FACEBOOK_BUTTON_COLOR))),
),
),
),
],
);
}
_sendToServer() async {
if (_key.currentState.validate()) {
_key.currentState.save();
showProgress(context, 'Creating new account...', false);
var profilePicUrl = '';
try {
AuthResult result = await FirebaseAuth.instance
.createUserWithEmailAndPassword(email: email, password: password);
if (_image != null) {
updateProgress('Uploading image...');
profilePicUrl = await FireStoreUtils()
.uploadUserImageToFireStorage(_image, result.user.uid);
}
User user = User(
email: email,
firstName: firstName,
phoneNumber: mobile,
userID: result.user.uid,
active: true,
lastName: lastName,
settings: Settings(allowPushNotifications: true),
profilePictureURL: profilePicUrl);
await FireStoreUtils.firestore
.collection(Constants.USERS)
.document(result.user.uid)
.setData(user.toJson());
hideProgress();
MyAppState.currentUser = user;
pushAndRemoveUntil(context, HomeScreen(user: user), false);
} catch (error) {
hideProgress();
(error as PlatformException).code != 'ERROR_EMAIL_ALREADY_IN_USE'
? showAlertDialog(context, 'Failed', 'Couldn\'t sign up')
: showAlertDialog(context, 'Failed',
'Email already in use. Please pick another email address');
print(error.toString());
}
} else {
print('false');
setState(() {
_validate = true;
});
}
}
#override
void dispose() {
_passwordController.dispose();
_image = null;
super.dispose();
}
}
helper:
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:progress_dialog/progress_dialog.dart';
String validateName(String value) {
String pattern = r'(^[a-zA-Z ]*$)';
RegExp regExp = new RegExp(pattern);
if (value.length == 0) {
return "Name is required";
} else if (!regExp.hasMatch(value)) {
return "Name must be a-z and A-Z";
}
return null;
}
String validateMobile(String value) {
String pattern = r'(^[0-9]*$)';
RegExp regExp = new RegExp(pattern);
if (value.length == 0) {
return "Mobile phone number is required";
} else if (!regExp.hasMatch(value)) {
return "Mobile phone number must contain only digits";
}
return null;
}
String validatePassword(String value) {
if (value.length < 6)
return 'Password must be more than 5 charaters';
else
return null;
}
String validateEmail(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 'Enter Valid Email';
else
return null;
}
String validateConfirmPassword(String password, String confirmPassword) {
print("$password $confirmPassword");
if (password != confirmPassword) {
return 'Password doesn\'t match';
} else if (confirmPassword.length == 0) {
return 'Confirm password is required';
} else {
return null;
}
}
//helper method to show progress
ProgressDialog progressDialog;
showProgress(BuildContext context, String message, bool isDismissible) async {
progressDialog = new ProgressDialog(context,
type: ProgressDialogType.Normal, isDismissible: isDismissible);
progressDialog.style(
message: message,
borderRadius: 10.0,
backgroundColor: Colors.deepOrange[900],
progressWidget: Container(
padding: EdgeInsets.all(8.0),
child: CircularProgressIndicator(
backgroundColor: Colors.white,
)),
elevation: 10.0,
insetAnimCurve: Curves.easeInOut,
messageTextStyle: TextStyle(
color: Colors.white, fontSize: 19.0, fontWeight: FontWeight.w600));
await progressDialog.show();
}
updateProgress(String message) {
progressDialog.update(message: message);
}
hideProgress() async {
await progressDialog.hide();
}
//helper method to show alert dialog
showAlertDialog(BuildContext context, String title, String content) {
// set up the AlertDialog
Widget okButton = FlatButton(
child: Text("OK"),
onPressed: () {
Navigator.pop(context);
},
);
AlertDialog alert = AlertDialog(
title: Text(title),
content: Text(content),
actions: [
okButton,
],
);
// show the dialog
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}
pushReplacement(BuildContext context, Widget destination) {
Navigator.of(context).pushReplacement(
new MaterialPageRoute(builder: (context) => destination));
}
push(BuildContext context, Widget destination) {
Navigator.of(context)
.push(new MaterialPageRoute(builder: (context) => destination));
}
pushAndRemoveUntil(BuildContext context, Widget destination, bool predict) {
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (context) => destination),
(Route<dynamic> route) => predict);
}
Widget displayCircleImage(String picUrl, double size, hasBorder) =>
CachedNetworkImage(
imageBuilder: (context, imageProvider) =>
_getCircularImageProvider(imageProvider, size, false),
imageUrl: picUrl,
placeholder: (context, url) =>
_getPlaceholderOrErrorImage(size, hasBorder),
errorWidget: (context, url, error) =>
_getPlaceholderOrErrorImage(size, hasBorder));
Widget _getPlaceholderOrErrorImage(double size, hasBorder) => Container(
width: size,
height: size,
decoration: BoxDecoration(
color: const Color(0xff7c94b6),
borderRadius: new BorderRadius.all(new Radius.circular(size / 2)),
border: new Border.all(
color: Colors.white,
width: hasBorder ? 2.0 : 0.0,
),
),
child: ClipOval(
child: Image.asset(
'assets/images/placeholder.jpg',
fit: BoxFit.cover,
height: size,
width: size,
)),
);
Widget _getCircularImageProvider(
ImageProvider provider, double size, bool hasBorder) {
return Container(
width: size,
height: size,
decoration: BoxDecoration(
color: const Color(0xff7c94b6),
borderRadius: new BorderRadius.all(new Radius.circular(size / 2)),
border: new Border.all(
color: Colors.white,
width: hasBorder ? 2.0 : 0.0,
),
),
child: ClipOval(
child: FadeInImage(
fit: BoxFit.cover,
placeholder: Image.asset(
'assets/images/placeholder.jpg',
fit: BoxFit.cover,
height: size,
width: size,
).image,
image: provider)),
);
}
Related
I was using Firestore database for the flutter app, so on the user profile screen, some data"mobile&email" doesn't appear when fetching user data.
I don't understand why it does not appear cuz I used the same code with driver user and student and it's worked.
profile screen, the third field for mobile number and the fourth for email
this's Profile screen code:
class SupervisorProfileScreen extends StatefulWidget {
const SupervisorProfileScreen({Key? key}) : super(key: key);
#override
State<SupervisorProfileScreen> createState() => _SupervisorProfileScreenState();
}
class _SupervisorProfileScreenState extends State<SupervisorProfileScreen> {
TextEditingController usernameController = TextEditingController();
TextEditingController nameController = TextEditingController();
TextEditingController mobileController = TextEditingController();
TextEditingController emailController = TextEditingController();
TextEditingController passwordController = TextEditingController();
SupervisorModel? supervisorModel;
#override
void initState() {
// TODO: implement initState
super.initState();
fetchLocalSupervisor();
}
void fetchLocalSupervisor() async {
SupervisorModel? user = await getLocalSuperVisor();
if (user != null) {
setState(() {
supervisorModel = user;
usernameController.text = user.userName ?? "";
nameController.text = user.name ?? "";
mobileController.text = user.mobile ?? "";
emailController.text = user.email ?? "";
passwordController.text = user.password ?? "";
});
}
}
/*
*/
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SizedBox(
height: 10.h,
),
Row(
children: [
InkWell(
onTap: () {
Get.back();
},
child: const Icon(
Icons.arrow_back_ios,
color: Colors.black,
),
),
const Expanded(
child: SizedBox(),
),
const Text(
"الملف الشخصي",
style: TextStyle(color: Color(0xff263238), fontSize: 20),
),
],
),
SizedBox(
height: 8.h,
),
Expanded(
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SizedBox(
width: 150.w,
height: 150.w,
child: Image.asset("assets/images/img_user2.png"),
),
SizedBox(
height: 10.h,
),
Padding(
padding: const EdgeInsets.only(bottom: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
SizedBox(
height: 33,
width: 235.w,
child: TextField(
controller: usernameController,
textAlign: TextAlign.right,
readOnly: true,
decoration: InputDecoration(
contentPadding: const EdgeInsets.symmetric(
vertical: 0.0, horizontal: 16),
enabledBorder: const OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(25)),
borderSide: BorderSide(
color: Colors.transparent, width: 0.0),
),
focusedBorder: const OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(25)),
borderSide: BorderSide(
color: Colors.transparent, width: 0.0),
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: const BorderSide(
color: Colors.transparent, width: 0.0),
),
filled: true,
hintText: "",
hintStyle: TextStyle(
fontSize: 14.sp,
color: const Color(0xffB6B7B7)),
fillColor: const Color(0xffF2F2F2)),
),
),
const Text(
"اسم المسخدم",
style: TextStyle(
color: Color(0xff263238), fontSize: 14),
),
],
),
),
Padding(
padding: const EdgeInsets.only(bottom: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
SizedBox(
height: 33,
width: 235.w,
child: TextField(
controller: nameController,
readOnly: true,
textAlign: TextAlign.right,
keyboardType: TextInputType.number,
decoration: InputDecoration(
contentPadding: const EdgeInsets.symmetric(
vertical: 0.0, horizontal: 16),
enabledBorder: const OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(25)),
borderSide: BorderSide(
color: Colors.transparent, width: 0.0),
),
focusedBorder: const OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(25)),
borderSide: BorderSide(
color: Colors.transparent, width: 0.0),
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: const BorderSide(
color: Colors.transparent, width: 0.0),
),
filled: true,
hintText: "",
hintStyle: TextStyle(
fontSize: 14.sp,
color: const Color(0xffB6B7B7)),
fillColor: const Color(0xffF2F2F2)),
),
),
const Text(
"الاسم",
style: TextStyle(
color: Color(0xff263238), fontSize: 14),
),
],
),
),
Padding(
padding: const EdgeInsets.only(bottom: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
SizedBox(
height: 33,
width: 235.w,
child: TextField(
controller: mobileController,
inputFormatters: [
LengthLimitingTextInputFormatter(10),
],
keyboardType: TextInputType.number,
style: const TextStyle(fontFamily: "Roboto"),
textAlign: TextAlign.right,
decoration: InputDecoration(
prefixIcon: const Icon(Icons.edit, color: AppConstants.lightGreen,),
contentPadding: const EdgeInsets.symmetric(
vertical: 0.0, horizontal: 16),
enabledBorder: const OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(25)),
borderSide: BorderSide(
color: Colors.transparent, width: 0.0),
),
focusedBorder: const OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(25)),
borderSide: BorderSide(
color: Colors.transparent, width: 0.0),
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: const BorderSide(
color: Colors.transparent, width: 0.0),
),
filled: true,
hintText: "",
hintStyle: TextStyle(
fontSize: 14.sp,
color: const Color(0xffB6B7B7)),
fillColor: const Color(0xffF2F2F2)),
),
),
const Text(
"رقم الجوال",
style: TextStyle(
color: Color(0xff263238), fontSize: 14),
),
],
),
),
Padding(
padding: const EdgeInsets.only(bottom: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
SizedBox(
height: 33,
width: 235.w,
child: TextField(
controller: emailController,
keyboardType: TextInputType.emailAddress,
style: const TextStyle(fontFamily: "Roboto"),
textAlign: TextAlign.right,
decoration: InputDecoration(
prefixIcon: const Icon(Icons.edit, color: AppConstants.lightGreen,),
contentPadding: const EdgeInsets.symmetric(
vertical: 0.0, horizontal: 16),
enabledBorder: const OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(25)),
borderSide: BorderSide(
color: Colors.transparent, width: 0.0),
),
focusedBorder: const OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(25)),
borderSide: BorderSide(
color: Colors.transparent, width: 0.0),
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: const BorderSide(
color: Colors.transparent, width: 0.0),
),
filled: true,
hintText: "",
hintStyle: TextStyle(
fontSize: 14.sp,
color: const Color(0xffB6B7B7)),
fillColor: const Color(0xffF2F2F2)),
),
),
const Text(
"البريد الالكتروني",
style: TextStyle(
color: Color(0xff263238), fontSize: 14),
),
],
),
),
Padding(
padding: const EdgeInsets.only(bottom: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
SizedBox(
height: 33,
width: 235.w,
child: TextField(
controller: passwordController,
style: const TextStyle(fontFamily: "Roboto"),
textAlign: TextAlign.right,
obscureText: true,
decoration: InputDecoration(
prefixIcon:
const Icon(Icons.edit, color: AppConstants.lightGreen,),
contentPadding: const EdgeInsets.symmetric(
vertical: 0.0, horizontal: 16),
enabledBorder: const OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(25)),
borderSide: BorderSide(
color: Colors.transparent, width: 0.0),
),
focusedBorder: const OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(25)),
borderSide: BorderSide(
color: Colors.transparent, width: 0.0),
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: const BorderSide(
color: Colors.transparent, width: 0.0),
),
filled: true,
hintText: "",
hintStyle: TextStyle(
fontSize: 14.sp,
color: const Color(0xffB6B7B7)),
fillColor: const Color(0xffF2F2F2)),
),
),
const Text(
"كلمة المرور",
style: TextStyle(
color: Color(0xff263238), fontSize: 14),
),
],
),
),
SizedBox(
height: 10.h,
),
Row(
children: [
InkWell(
onTap: () {
if (validateEmail(emailController.text)==true) {
Alert(
context: context,
type: AlertType.warning,
desc: "هل أنت متأكد من حفظ البيانات ؟",
buttons: [
DialogButton(
radius: BorderRadius.circular(20),
width: 90,
height: 34,
child: const Text(
"نعم",
style: TextStyle(
color: Colors.black,
fontSize: 20),
),
onPressed: () async {
Navigator.pop(context);
bool sts = await updateSupervisorData(
supervisorModel?.uid ?? "",
nameController.text,
mobileController.text,
emailController.text,
passwordController.text,);
if (sts) {
Fluttertoast.showToast(
msg: "تم الحفظ بنجاح");
} else {
Fluttertoast.showToast(
msg:
"عذراً حصل خطأ، يرجى المحاولة لاحقاً");
}
},
color: AppConstants.lightGreen,
),
],
).show();
};
},
child: Container(
width: 90,
height: 34,
decoration: BoxDecoration(
color: const Color(0xff9BF1AF),
borderRadius: BorderRadius.circular(28),
),
child: const Center(
child: Text(
"حفظ", //save
style: TextStyle(
color: Color(0xff263238), fontSize: 16),
),
),
),
),
const Expanded(
child: SizedBox(),
),
],
),
],
),
))
],
),
),
),
);
}
}
and this's the body of function getLocalSuperVisor
Future<SupervisorModel?> getLocalSuperVisor() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String? us = prefs.getString('supervisorObject');
if (us != null) {
SupervisorModel userObj = SupervisorModel.fromJson(json.decode(us));
return userObj;
} else {
return null;
}
}
supervisorModel:
class SupervisorModel {
String? uid;
String? mobile;
String? email;
String? userName;
String? password;
String? name;
SupervisorModel({
this.uid,
this.mobile,
this.email,
this.userName,
this.password,
this.name,
});
Map<String, dynamic> toJson() {
return {
FirebaseConstants.pathUid: uid,
FirebaseConstants.pathUserMobile: mobile,
FirebaseConstants.pathEmail: email,
FirebaseConstants.pathUserName: userName,
FirebaseConstants.pathUserPassword: password,
FirebaseConstants.pathName: name,
};
}
factory SupervisorModel.fromJson(Map<String, dynamic> json) =>
SupervisorModel(
uid: json[FirebaseConstants.pathUid],
mobile: json[FirebaseConstants.pathUserMobile],
email: json[FirebaseConstants.pathEmail],
userName: json[FirebaseConstants.pathUserName],
password: json[FirebaseConstants.pathUserPassword],
name: json[FirebaseConstants.pathName],
);
factory SupervisorModel.fromDocument(DocumentSnapshot doc) {
String uid = "";
String mobile = "";
String email = "";
String userName = "";
String password = "";
String name = "";
try {
uid = doc.id;
} catch (e) {}
try {
name = doc.get(FirebaseConstants.pathUserMobile);
} catch (e) {
}
try {
name = doc.get(FirebaseConstants.pathEmail);
} catch (e) {
// print(e.toString());
}
try {
userName = doc.get(FirebaseConstants.pathUserName);
} catch (e) {}
try {
password = doc.get(FirebaseConstants.pathUserPassword);
} catch (e) {}
try {
name = doc.get(FirebaseConstants.pathName);
} catch (e) {
// print(e.toString());
}
return SupervisorModel(
uid: uid,
mobile: mobile,
email: email,
userName: userName,
password: password,
name: name,
);
}
}
firebase Constants :
class FirebaseConstants {
// User Constants
static const pathStudentUserCollection = "students";
static const pathName = "name";
static const pathUserId = "id";
static const pathUserMobile = "mobile";
static const pathUserPassword = "password";
static const pathEmail = "email";
static const pathFatherName = "fatherName";
static const pathFatherMobile = "fatherMobile";
static const pathDirection = "direction";
static const pathAddress = "address";
static const pathDays = "days";
static const pathUid = "uid";
static const pathOnBus = "on_bus";
static const pathIsAttending = "is_attending";
// Supervisor
static const pathUserName = "user_name";
static const pathSupervisorsCollection = "supervisors";
// Driver
static const pathDriversCollection = "drivers";
}
the data is saved in the database correctly but when getting data it does not appear
I'm a beginner programmer and started recently with flutter and I can't solve this problem.
Here is my parent class :
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:todo_n_f_t_app/app/data/database.dart';
import 'package:todo_n_f_t_app/app/data/user.dart';
import 'package:todo_n_f_t_app/app/data/user_controller.dart';
import 'app/modules/login/views/login_view.dart';
import 'constants/firebase_constants.dart';
class AuthController extends GetxController {
static AuthController instance = Get.find();
late Rx<User?> _user;
#override
void onReady() {
super.onReady();
_user = Rx<User?>(auth.currentUser);
_user.bindStream(auth.userChanges());
ever(_user, _initialScreen);
}
_initialScreen(User? user) {
if (user == null) {
Get.offAll(() => LoginView());
} else {
Get.offAll(() => LoginView());
}
}
void register(String email, String password, String name) async {
try {
UserCredential _authResult = await auth.createUserWithEmailAndPassword(
email: email, password: password);
UserModel _user = UserModel(
id: _authResult.user?.uid,
name: name,
email: _authResult.user?.email,
);
if (await Database().createNewUser(_user)) {
Get.find<UserController>().user = _user;
Get.back();
}
} on FirebaseAuthException catch (e) {
print(e.message);
// Get.snackbar("Error", e.message!);
Get.snackbar(
"Error",
e.message!,
snackPosition: SnackPosition.BOTTOM,
);
} catch (e) {
print(e.toString());
}
}
void login(String email, password) async {
try {
await auth.signInWithEmailAndPassword(email: email, password: password);
} catch (e) {
Get.snackbar("About User", "User message",
snackPosition: SnackPosition.BOTTOM,
titleText: Text("Acount creation failed"),
messageText:
Text(e.toString(), style: TextStyle(color: Colors.white)));
}
}
void signOut() {
try {
auth.signOut();
} catch (e) {
print(e.toString());
}
}
}
Here is the derived class:
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:todo_n_f_t_app/auth_controller.dart';
class RegisterView extends GetView<AuthController> {
final TextEditingController _passwordTextController = TextEditingController();
final TextEditingController _emailTextController = TextEditingController();
final TextEditingController _usernameTextController = TextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
body: Container(
child: SafeArea(
left: false,
right: false,
child: Column(children: [
SizedBox(height: 40.0),
Container(
child: Container(
height: 100,
width: 100,
alignment: Alignment.center,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15.0),
gradient: SweepGradient(colors: [
Color(0xff998629),
Color(0xDE1C44D2),
Color(0xff582D95),
Color(0xffB10A3B),
Color(0xff269B27),
]),
),
child: Container(
height: 90,
width: 90,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15.0),
color: Color(0xB3000000),
),
child: Icon(Icons.done_outline,
color: Colors.white, size: 80.0),
),
)),
SizedBox(
height: 10,
),
Expanded(
child: Text(
'TodoNFT',
style: TextStyle(fontSize: 36.0),
)),
SizedBox(
width: MediaQuery.of(context).size.width,
height: 4,
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(colors: [
Color(0xff1C44D2),
Color(0xff582D95),
Color(0xffB10A3B),
Color(0xff998629),
Color(0xff269B27),
])),
),
),
SizedBox(
height: 60.0,
),
Container(
width: MediaQuery.of(context).size.width - 20.0,
child: TextField(
controller: _emailTextController,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(20.0),
),
filled: true,
fillColor: Color(0x33EBC4C4),
hintText: 'Email',
hintStyle: TextStyle(fontSize: 24.0, color: Colors.white),
suffix: Icon(Icons.mail_outline,
color: Colors.white, size: 24.0),
),
),
),
SizedBox(height: 60),
Container(
width: MediaQuery.of(context).size.width - 20.0,
child: TextField(
controller: _passwordTextController,
obscureText: true,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(20.0),
),
filled: true,
fillColor: Color(0x33EBC4C4),
hintText: 'Password',
hintStyle: TextStyle(fontSize: 24.0, color: Colors.white),
suffix: Icon(Icons.lock, color: Colors.white, size: 24.0),
),
),
),
SizedBox(height: 60),
Container(
width: MediaQuery.of(context).size.width - 20.0,
child: TextField(
controller: _usernameTextController,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(20.0),
),
filled: true,
fillColor: Color(0x33EBC4C4),
hintText: 'Username',
hintStyle: TextStyle(fontSize: 24.0, color: Colors.white),
suffix: Icon(Icons.mail_outline,
color: Colors.white, size: 24.0),
),
),
),
SizedBox(height: 40),
SizedBox(
width: MediaQuery.of(context).size.width - 40.0,
height: 4,
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(colors: [
Color(0xff1C44D2),
Color(0xff582D95),
Color(0xffB10A3B),
Color(0xff998629),
Color(0xff269B27),
])),
),
),
SizedBox(height: 30.0),
TextButton(
child: Container(
child: Text(
'Register',
style: TextStyle(fontSize: 36.0, color: Colors.white),
),
),
onPressed: () {
controller.register(
_emailTextController.text,
_passwordTextController.text,
_usernameTextController.text);
},
),
SizedBox(height: 30.0),
]),
),
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/Background.png"),
fit: BoxFit.cover,
),
)));
}
}
How can I invoke the register method from AuthController? I bolded onPressed method in RegisterView, I don't have any errors in editor but code breaks when I want to register. Also, it doesn't write user uid in firestore collection.
I tried to register user into FireStore and I get authenticated user but I don't get new collection with uid from user I get in authenticated.
my signup.dart file:
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
class SignUp extends StatefulWidget {
#override
_SignUpState createState() => _SignUpState();
}
class _SignUpState extends State<SignUp> {
final FirebaseAuth firebaseAuth = FirebaseAuth.instance;
final _formKey = GlobalKey<FormState>();
TextEditingController _emailTextController = TextEditingController();
TextEditingController _passwordTextController = TextEditingController();
TextEditingController _nameTextController = TextEditingController();
TextEditingController _confirmPasswordTextController =
TextEditingController();
String gender;
String groupValue = "Erkek";
bool loading = false;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: <Widget>[
Image.asset(
'images/backg.jpg',
fit: BoxFit.fill,
width: double.infinity,
height: double.infinity,
),
Container(
color: Colors.black.withOpacity(0.4),
width: double.infinity,
height: double.infinity,
),
Padding(
padding: const EdgeInsets.only(top: 200.0),
child: Center(
child: Form(
key: _formKey,
child: ListView(
children: <Widget>[
Padding(
padding:
const EdgeInsets.fromLTRB(14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(20.0),
color: Colors.white.withOpacity(0.4),
elevation: 0.0,
child: Padding(
padding: const EdgeInsets.only(left: 12.0),
child: ListTile(
title: TextFormField(
controller: _passwordTextController,
decoration: InputDecoration(
hintText: "Ad Soyad",
icon: Icon(Icons.person),
border: InputBorder.none
),
// ignore: missing_return
validator: (value) {
if (value.isEmpty) {
return "İsim boşluğu doldurulmalıdır.";
}
return null;
},
// ignore: missing_return
),
trailing: Icon(Icons.remove_red_eye),
),
),
),
),
Padding(
padding:
const EdgeInsets.fromLTRB(14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(20.0),
color: Colors.white.withOpacity(0.4),
elevation: 0.0,
child: Padding(
padding: const EdgeInsets.only(left: 12.0),
child: TextFormField(
controller: _emailTextController,
decoration: InputDecoration(
hintText: "Email",
icon: Icon(Icons.email),
border: InputBorder.none
),
// ignore: missing_return
validator: (value) {
if (value.isEmpty) {
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 "Lütfen geçerli bir mail adresi giriniz.";
else
return null;
}
}),
),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(14.0, 8.0, 14.0, 8.0),
child: new Container(
color: Colors.white.withOpacity(0.4),
child: Row(
children: <Widget>[
Expanded(
child: ListTile(
title: Text(
"Erkek",
textAlign: TextAlign.end ,
style: TextStyle(color: Colors.white),
),
trailing: Radio(value: "Erkek", groupValue: groupValue, onChanged: (e)=>valueChanged(e)),
)),
Expanded(
child: ListTile(
title: Text(
"Kadın",
textAlign: TextAlign.end ,
style: TextStyle(color: Colors.white),
),
trailing: Radio(value: "Kadın", groupValue: groupValue, onChanged: (e)=>valueChanged(e)),
)),
],
),
),
),
Padding(
padding:
const EdgeInsets.fromLTRB(14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(20.0),
color: Colors.white.withOpacity(0.4),
elevation: 0.0,
child: Padding(
padding: const EdgeInsets.only(left: 12.0),
child: ListTile(
title: TextFormField(
controller: _passwordTextController,
obscureText: true,
decoration: InputDecoration(
hintText: "Şifre",
icon: Icon(Icons.lock_outline),
border: InputBorder.none
),
// ignore: missing_return
validator: (value) {
if (value.isEmpty) {
return "Şifre boşluğu doldurulmalıdır.";
} else if (value.length < 6) {
return "Şifre 6 haneden uzun olmalı!";
}
return null;
},
// ignore: missing_return
),
trailing : IconButton(icon: Icon(Icons.remove_red_eye), onPressed: (){})
),
),
),
),
Padding(
padding:
const EdgeInsets.fromLTRB(14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(20.0),
color: Colors.white.withOpacity(0.4),
elevation: 0.0,
child: Padding(
padding: const EdgeInsets.only(left: 12.0),
child: ListTile(
title : TextFormField(
controller: _confirmPasswordTextController,
obscureText: true,
decoration: InputDecoration(
hintText: "Şifreyi Doğrula",
icon: Icon(Icons.lock_outline),
border: InputBorder.none
),
// ignore: missing_return
validator: (value) {
if (value.isEmpty) {
return "Şifre boşluğu doldurulmalıdır.";
} else if (value.length < 6) {
return "Şifre 6 haneden uzun olmalı!";
}else if (_passwordTextController != value){
return "Şifreler uyuşmuyor.";
}
return null;
},
// ignore: missing_return
),
trailing : IconButton(icon: Icon(Icons.remove_red_eye), onPressed: (){}),
),
),
),
),
Padding(
padding:
const EdgeInsets.fromLTRB(12.0, 8.0, 12.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(20.0),
color: Colors.red.withOpacity(0.8),
elevation: 0.0,
child: MaterialButton(
onPressed: () {
validateForm();
},
minWidth: MediaQuery.of(context).size.width,
child: Text(
"Kayıt Ol",
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 15.0),
),
)),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: InkWell(
onTap: () {
Navigator.pop(context);
},
child: Text(
"Giriş Yap",
textAlign: TextAlign.center,
style: TextStyle(color: Colors.red),
))),
],
)),
),
),
Visibility(
visible: loading ?? true,
child: Center(
child: Container(
alignment: Alignment.center,
color: Colors.white.withOpacity(0.9),
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(Colors.red),
),
),
))
],
),
);
}
valueChanged(e) {
setState(() {
if (e == "Erkek") {
groupValue = e;
gender = e;
} else if (e == "Kadın") {
groupValue = e;
gender = e;
}
});
}
void validateForm() async{
FormState formState = _formKey.currentState;
if(formState.validate()){
User user = await firebaseAuth.currentUser;
if(user == null){
firebaseAuth.createUserWithEmailAndPassword(email: _emailTextController, password: _passwordTextController).then((user) => {
});
}
}
}
}
My Showing errors.
Performing hot reload...
Syncing files to device sdk gphone x86...
lib/pages/signup.dart:276:60: Error: The argument type 'TextEditingController' can't be assigned to the parameter type 'String'.
'TextEditingController' is from 'package:flutter/src/widgets/editable_text.dart' ('/C:/src/flutter/packages/flutter/lib/src/widgets/editable_text.dart').
firebaseAuth.createUserWithEmailAndPassword(email: _emailTextController, password: _passwordTextController).then((user) => {
^
lib/pages/signup.dart:276:92: Error: The argument type 'TextEditingController' can't be assigned to the parameter type 'String'.
'TextEditingController' is from 'package:flutter/src/widgets/editable_text.dart' ('/C:/src/flutter/packages/flutter/lib/src/widgets/editable_text.dart').
firebaseAuth.createUserWithEmailAndPassword(email: _emailTextController, password: _passwordTextController).then((user) => {
^
==========NEW ERRORRR=================
void validateForm() async {
FormState formState = _formKey.currentState;
if (formState.validate()) {
User user = await firebaseAuth.currentUser;
if (user == null) {
firebaseAuth
.createUserWithEmailAndPassword(
email: _emailTextController.text,
password: _passwordTextController.text)
.then((user) => {
_userServices.createUser(
{
"username": _nameTextController.text,
"email": user.email
}
)
});
}
}
}
}
Use _emailTextController.text instead of just _emailTextController.
I am creating a flutter app and I am using firestore as the backend. I intend to add data to the backend from the app on a button click. I have the needed variables for those data and also called an instance of firestore. The problem now is when I click on the add button, though the fields are created in firestore, the values are null. I have read what others have written about it from here but it looks like the solution provided here does not tackle my problem.
What could I be doing wrong? Below is an excerpt of my code and shot of my backend.
class SoftwareIssuesContactForm extends StatefulWidget {
#override
_SoftwareIssuesContactFormState createState() =>
_SoftwareIssuesContactFormState();
}
class _SoftwareIssuesContactFormState extends State<SoftwareIssuesContactForm> {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
List<String> _semesters = <String>['', 'Semester 1', 'Semester 2',
'Semester 3', 'Semester 4', 'Semester 5', 'Semester 6', 'Semester 7',
'Semester 8'];
String _stNumber;
String _stEmail;
String _query;
String _dropdownError;
String _stPhone;
String _selectedItem;
bool _autoValidate = false;
String _semester = '';
String uid;
// Contact newContact = Contact();
final FocusNode myFocusNodeEmail = FocusNode();
final FocusNode myFocusNodeName = FocusNode();
TextEditingController studentNumberController = TextEditingController();
TextEditingController studentEmailController = TextEditingController();
TextEditingController queryController = TextEditingController();
TextEditingController studentPhoneNumberController = TextEditingController();
PageController _pageController;
#override
void dispose() {
myFocusNodeEmail.dispose();
myFocusNodeName.dispose();
_pageController?.dispose();
super.dispose();
}
#override
void initState() {
super.initState();
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
_pageController = PageController();
}
// ignore: slash_for_doc_comments
/**********************************************************
######## FOR VALIDATING STUDENT NUMBER #######
*********************************************************/
String validateStudentNumber(String value){
if (value.isEmpty) {
return 'Student Number is required';
}
else {
return null;
}
}
// ignore: slash_for_doc_comments
/**********************************************************
######## FOR VALIDATING PHONE NUMBER #######
*********************************************************/
String validateStudentPhoneNumber(String value){
String pattern = r'(^(?:[+0]9)?[0-9]{10,12}$)';
RegExp regExp = RegExp(pattern);
if (value == null) return 'Phone Number is required';
// else if (value.length != 10) {
// return 'Phone Number must be of 10 digits';
// }
else if (!regExp.hasMatch(value)) {
return 'Enter a valid Phone Number';
}
return null;
}
// ignore: slash_for_doc_comments
/**********************************************************
######## FOR VALIDATING EMAIL ADDRESS #######
*********************************************************/
String validateStudentEmailAddress (String value){
Pattern pattern =
r'^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}'
r'\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
RegExp regex = RegExp(pattern);
if (value.isEmpty) return 'Your Email Address is required';
if (!regex.hasMatch(value))
return 'Enter a valid Email Address';
else
return null;
}
// ignore: slash_for_doc_comments
/**********************************************************
######## FOR VALIDATING ENQUIRIES #######
*********************************************************/
String validateStudentQuery(String value){
if (value.isEmpty) {
return 'You forgot to state the problem...';
}
else {
return null;
}
}
// ignore: slash_for_doc_comments
/*******************************************************************
##### CHECKING IF FORM IS VALID BEFORE SUBMITTING ######
*******************************************************************/
bool validateAndSave(){
final form = _formKey.currentState;
if(form.validate()){
form.save();
return true;
}
else {
return false;
}
}
// ignore: slash_for_doc_comments
/**********************************************************
####### VALIDATING FORM BEFORE SUBMITTING ########
***********************************************************/
validateAndSubmit(){
if (validateAndSave()) {
try{
// Navigator.pushReplacement(context,
// MaterialPageRoute(builder: (context) => DashboardScreen()),
// );
/**********************************************************
####### SHOW DIALOG ON SUBMIT ########
***********************************************************/
return showDialog(
barrierDismissible: false,
context: context,
builder: (BuildContext context){
return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50),
),
elevation: 6,
backgroundColor: Colors.transparent,
child: _buildDialogContent(context),
);
}
);
}
catch(e){
print(e);
}
}
else {
setState(() {
_autoValidate = true;
});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color(0xFF56ccf2),
// backgroundColor: Colors.grey[100],
body: SafeArea(
top: false,
bottom: false,
child: SingleChildScrollView(
child: Container(
// height: 600,
child: Column(
children: [
Padding(
padding: EdgeInsets.only(top: 30,),
child: Text(
"IT SUPPORT QUERY FORM",
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.bold,
// fontStyle: FontStyle.italic,
),
),
),
Padding(
padding: EdgeInsets.only(
top: 10.0, bottom: 5.0, left: 15.0, right: 15.0),
child: Card(
elevation: 6,
child: Form(
key: _formKey,
autovalidate: _autoValidate,
child: ListView(
shrinkWrap: true, // use this
padding: EdgeInsets.symmetric(horizontal: 20.0),
children: <Widget>[
//===> Email Number Text Input starts from here <===
Padding(
padding: EdgeInsets.only(
top: 10.0, bottom: 6.0, left: 1.0, right: 1.0),
child: TextFormField(
autofocus: false,
focusNode: myFocusNodeEmail,
controller: studentNumberController,
keyboardType: TextInputType.emailAddress,
style: TextStyle(
fontSize: 16.0,
color: Colors.black),
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
// icon: Icon(Icons.person),
// hintText: 'Enter your first and last name',
labelText: 'Student Number',
),
validator: validateStudentNumber,
onSaved: (String val) {
_stNumber = val;
},
),
),
// Padding(
// padding: EdgeInsets.only(
// top: 5.0, bottom: 10.0, left: 1.0, right: 1.0),
// child: TextFormField(
// decoration: InputDecoration(
// border: OutlineInputBorder(
// borderRadius: BorderRadius.circular(20.0),
// ),
// // icon: const Icon(Icons.phone),
// // hintText: 'Enter a phone number',
// labelText: 'Phone',
// ),
// keyboardType: TextInputType.phone,
// inputFormatters: [
// WhitelistingTextInputFormatter.digitsOnly,
// ],
// ),
// ),
//===> Email Address Text Input starts from here <===
Padding(
padding: EdgeInsets.only(
top: 1.0, bottom: 6.0, left: 1.0, right: 1.0),
child: TextFormField(
validator: validateStudentEmailAddress,
onSaved: (String val) {
_stEmail = val;
},
controller: studentEmailController,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
// icon: const Icon(Icons.email),
// hintText: 'Enter a email address',
labelText: 'Student Email',
),
keyboardType: TextInputType.emailAddress,
style: TextStyle(
fontSize: 16.0,
color: Colors.black),
),
),
//===> Phone Number Text Input starts from here <===
Padding(
padding: EdgeInsets.only(
top: 1.0, bottom: 6.0, left: 1.0, right: 1.0),
child: TextFormField(
validator: validateStudentPhoneNumber,
onSaved: (String val) {
_stPhone = val;
},
controller: studentPhoneNumberController,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
// icon: const Icon(Icons.email),
// hintText: 'Enter a email address',
labelText: 'Phone Number',
),
keyboardType: TextInputType.phone,
inputFormatters: [
FilteringTextInputFormatter.allow(
RegExp(r'^[()\d -]{1,15}$')),
],
style: TextStyle(
fontSize: 16.0,
color: Colors.black),
),
),
//===> Drop Down Menu starts from here <===
Padding(
padding: EdgeInsets.only(top: 1.0, bottom: 6.0, left: 1.0, right: 1.0),
child: FormField(
builder: (FormFieldState state) {
return InputDecorator(
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
// icon: const Icon(Icons.color_lens),
labelText: 'Semester',
hintText: ("Semester"),
),
isEmpty: _semester == '',
child: Padding(
padding: EdgeInsets.only(left: 1.0, right: 130 , ),
child: Container(
// height: 55, //gives the height of the dropdown button
width: MediaQuery.of(context).size.width,
child: DropdownButtonHideUnderline( // to hide the default underline of the dropdown button
child: ButtonTheme(
alignedDropdown: true, //If false (the default), then the dropdown's menu will be wider than its button.
child: DropdownButton(
value: _semester,
isDense: true,
elevation: 5,
isExpanded: true,
onChanged: (String value) {
setState(() {
_semester = value; // saving the selected value
state.didChange(value);
});
},
items: _semesters.map((String value) {
return DropdownMenuItem(
value: value, // displaying the selected value
child: Text(value ?? '',
textAlign: TextAlign.left,
overflow: TextOverflow.ellipsis,
maxLines: 1,
softWrap: true,
),
);
}).toList(),
),
),
),
),
),
);
},
),
),
//===> Query Text Input starts from here <===
TextFormField(
validator: validateStudentQuery,
onSaved: (String val) {
_query = val;
},
controller: queryController,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
// icon: const Icon(Icons.email),
// hintText: 'Enter your query',
labelText: 'Your Query',
),
keyboardType: TextInputType.text,
style: TextStyle(
fontSize: 16.0,
color: Colors.black),
maxLines: 3,
),
// ignore: slash_for_doc_comments
/**********************************************************
####### FOR SUBMIT BUTTON ########
***********************************************************/
Container(
// padding: EdgeInsets.only(left: 1.0, top: 10.0),
margin: EdgeInsets.only(top: 6.0, bottom: 5),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(10.0)),
boxShadow: <BoxShadow>[
BoxShadow(
color: Color(0xFF008ECC),
offset: Offset(0.0, 0.0),
//blurRadius: 20.0,
),
BoxShadow(
color: Color(0xFF008ECC),
offset: Offset(0.0, 0.0),
//blurRadius: 20.0,
),
],
gradient: LinearGradient(
colors: [
Color(0xFF008ECC), //Colors is Olympic blue
Color(0xFF008ECC),
],
begin: FractionalOffset(0.2, 0.2),
end: FractionalOffset(1.0, 1.0),
stops: [0.0, 1.0],
tileMode: TileMode.clamp),
),
child: MaterialButton(
onPressed: validateAndSubmit,
child: Padding(
padding: EdgeInsets.symmetric(
vertical: 10.0, horizontal: 65.0),
child: Text(
"Submit",
style: TextStyle(
color: Colors.white,
fontSize: 25.0,
),
),
),
)),
],
)),
),
),
],
),
),
)),
);
}
}
// ignore: slash_for_doc_comments
/**********************************************************
### IMPLEMENTATION OF _buildDialogContent METHOD ###
***********************************************************/
Widget _buildDialogContent(BuildContext context) => Container(
height: 230,
decoration: BoxDecoration(
color: Color(0xFF008ECC),
shape: BoxShape.rectangle,
borderRadius: BorderRadius.all(Radius.circular(12)),
),
child: Column(
children: <Widget>[
Container(
child: Padding(
padding: EdgeInsets.all(12.0),
child: Container(
height: 80, width: 80,
child: Icon(MdiIcons.vote,
size: 90,
color: Color(0xFF56ccf2),
),
),
),
width: double.infinity,
decoration: BoxDecoration(
color: Colors.white,
shape: BoxShape.rectangle,
borderRadius: BorderRadius.only(topLeft: Radius.circular(12),
topRight: Radius.circular(12)),
),
),
SizedBox(height: 24),
Padding(
padding: EdgeInsets.only(left: 5, right: 5),
child: Text("To submit the form tap Yes. tap No to edit the form".toUpperCase(),
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontSize: 17,
),
),
),
SizedBox(height: 10),
Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
FlatButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text("No".toUpperCase(),
style: TextStyle(
color: Colors.white,
),
),
),
SizedBox(width: 8),
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(10.0)),
boxShadow: <BoxShadow>[
BoxShadow(
color: Color(0xFF008ECC),
offset: Offset(0.0, 0.0),
//blurRadius: 20.0,
),
BoxShadow(
color: Color(0xFF008ECC),
offset: Offset(0.0, 0.0),
//blurRadius: 20.0,
),
],
gradient: LinearGradient(
colors: [
Color(0xFF008ECC), //Colors is Olympic blue
Color(0xFF008ECC),
],
begin: FractionalOffset(0.2, 0.2),
end: FractionalOffset(1.0, 1.0),
stops: [0.0, 1.0],
tileMode: TileMode.clamp),
),
child: RaisedButton(
onPressed: () {
_saveInput();
// Navigator.of(context).pop();
Navigator.pushReplacement(context,
MaterialPageRoute(builder: (context) => DashboardScreen()),
);
},
color: Colors.white,
child: Text("Yes".toUpperCase(),
style: TextStyle(
color: Colors.redAccent,
),
),
),
),
],
),
],
),
);
//This function adds the needed data to firestore.
void _saveInput () async{
String uid;
String _stName;
String _stSemester;
String _stNumber;
String _stEmail;
String _query;
String _stPhone;
String _selectedItem;
//Creating reference object for firestore
final db = FirebaseFirestore.instance;
print(_stName);
await FirebaseFirestore.instance.collection('software_issues').doc().set({
'Uid': uid,
'Student Name': _stName,
'Student Semester': _stSemester,
'Student Number': _stNumber,
'Student Email': _stEmail,
'Student Query': _query,
'Student Phone Num': _stPhone,
'Selected Item': _selectedItem,
});
Can you try:
Firestore.instance.collection('software_issues').document().setData(
your data
);
set merge property to true if you want to update it.
I have been trying to move to another page after register but it doesnt move to new page. it just saves data to data base and doesnt move. it remains on the same page. i need it to move to another page.
import 'package:flutter/material.dart';
import 'package:project_work/extra%20pages/screen/welcome.dart';
import 'LogIn.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'models.dart';
// had to switch the login part for sign up. So this page is Sign up.
class LogIn extends StatefulWidget {
#override
_LogInState createState() => new _LogInState();
}
class _LogInState extends State<LogIn> {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
final _user = User();
TextStyle style =
TextStyle(fontFamily: '', fontSize: 20.0, color: Colors.black);
#override
Widget build(BuildContext context) {
return Scaffold(
body: new Stack(
children: <Widget>[
Column(
children: <Widget>[
Padding(
padding: EdgeInsets.only(left: 10.0),
)
],
),
Center(
child: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/Artboardd.png"),
fit: BoxFit.cover,
),
),
alignment: Alignment.center,
padding: const EdgeInsets.all(36.0),
child: Builder(
builder: (context) => Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(height: 15.0),
Text(
"Register",
style: TextStyle(
color: Colors.black,
fontStyle: FontStyle.italic,
fontFamily: 'Pacifico',
fontSize: 50.0),
textAlign: TextAlign.center,
),
TextFormField(
obscureText: false,
style: style,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
labelText: 'Email',
contentPadding: EdgeInsets.fromLTRB(
20.0, 15.0, 20.0, 15.0),
border: OutlineInputBorder(
borderRadius:
BorderRadius.circular(32.0)),
icon: Icon(Icons.mail)),
validator: (value) {
if (value.isEmpty) {
return 'Please enter your Email';
}
return null;
},
onSaved: (val) =>
setState(() => _user.email = val),
),
SizedBox(height: 15.0),
TextFormField(
obscureText: true,
style: style,
keyboardType: TextInputType.text,
decoration: InputDecoration(
labelText: 'Password',
contentPadding: EdgeInsets.fromLTRB(
20.0, 15.0, 20.0, 15.0),
border: OutlineInputBorder(
borderRadius:
BorderRadius.circular(32.0)),
icon: Icon(Icons.vpn_key)),
validator: (value) {
if (value.isEmpty || value.length < 6) {
return 'Password must be at least 6 characters';
}
return null;
},
onSaved: (val) =>
setState(() => _user.password = val)),
Container(
padding: const EdgeInsets.symmetric(
vertical: 16.0, horizontal: 16.0),
child: RaisedButton(
padding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
shape: RoundedRectangleBorder(
borderRadius:
new BorderRadius.circular(18.0),
side: BorderSide(color: Colors.blue),
),
color: Colors.blue,
onPressed: signup,
child: Text('Register'))),
])))))
],
));
}
_showDialog(BuildContext context) {
Scaffold.of(context)
.showSnackBar(SnackBar(content: Text('Registered Succesfully')));
}
i cant tell if there is a problem with this code here. Can you please help
void signup()async {
if (_formKey.currentState.validate()) {
_formKey.currentState.save();
try {
FirebaseUser user = (await FirebaseAuth.instance
.createUserWithEmailAndPassword(
email: _user.email, password: _user.password)) as FirebaseUser;
user.sendEmailVerification();
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context)=> SignUp()));
} catch (e) {
print(e.messgae);
}
}
}
}
For me it works just using:
Navigator.push(context, MaterialPageRoute(builder: (context)=> Register(User: user,)));
Hope it helps!