Page not moving to the next page - firebase

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!

Related

How to access in flutter method in derived class from parent class?

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.

Error: The argument type 'TextEditingController' can't be assigned to the parameter type 'String'.in FLUTTER

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.

While creating new account screen keeps spinning in flutter

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

Flutter: Couldn't reach the class properties in Build Widget with Firebase connection

Everytime when I try to use loggegInUser property it returns null please help me to solve this issue
getCurrent() methods works properly and prints user email and password but I can not acces this variables in Build Widget.
class _ProfilePageState extends State<ProfilePage> {
final _auth = FirebaseAuth.instance;
FirebaseUser loggedInUser;
String uid;
var url;
var userProfilePhotoUrl;
int currentPageIndex = 2;
CircularBottomNavigationController _navigationController =
new CircularBottomNavigationController(2);
List<TabItem> tabItems = List.of([
new TabItem(Icons.home, "Home", Colors.blue,
labelStyle: TextStyle(fontWeight: FontWeight.normal)),
new TabItem(Icons.add, "Let's Party", Colors.orange,
labelStyle: TextStyle(color: Colors.red, fontWeight: FontWeight.bold)),
new TabItem(Icons.person, "Reports", Colors.red),
]);
#override
void initState() {
super.initState();
getCurrentUser();
}
void getCurrentUser() async {
try {
final user = await _auth.currentUser();
if (user != null) {
loggedInUser = user;
uid = user.uid;
print(loggedInUser.email);
print(uid);
}
} catch (e) {
print(e);
}
}
void changePage(int index) {
setState(() {
currentPageIndex = index;
});
}
Future<FirebaseImage> getFirebaseProfilPhoto() async {
try {
final user = await _auth.currentUser();
if (user != null) {
loggedInUser = user;
uid = user.uid;
print(loggedInUser.email);
print(uid);
return FirebaseImage(
'gs://homeparty-68792.appspot.com/user_profile_images/${loggedInUser.uid}.png');
}
} catch (e) {
print(e);
}
}
#override
Widget build(BuildContext context) {
setState(() {
getCurrentUser();
});
return Scaffold(
appBar: AppBar(
title: Text('furkanakguun'),
),
body: Builder(
builder: (context) => Container(
color: Colors.black,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
SizedBox(
height: 20.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CircleAvatar(
backgroundColor: Colors.black,
backgroundImage: FirebaseImage(
'gs://homeparty-68792.appspot.com/user_profile_images/${loggedInUser.uid}.png'),
// FirebaseImage(
// 'gs://homeparty-68792.appspot.com/user_profile_images/$uid.png'),
//backgroundImage: Image.network(userProfilePhotoUrl),
radius: 100,
),
Padding(
padding: EdgeInsets.only(top: 60.0),
child: IconButton(
icon: Icon(
FontAwesomeIcons.camera,
size: 30.0,
),
focusColor: Colors.white,
color: Colors.deepPurple,
onPressed: () {
print('asd');
Navigator.pushNamed(context, 'image_uploader');
},
),
),
],
),
Divider(),
SizedBox(
height: 20.0,
),
Row(
children: <Widget>[
Card(
color: Colors.grey[900],
margin: EdgeInsets.symmetric(horizontal: 10.0),
child: Icon(Icons.person),
),
Card(
color: Colors.grey[900],
margin:
EdgeInsets.symmetric(horizontal: 10.0, vertical: 7.0),
child: Container(
child: Column(
children: <Widget>[
Align(
alignment: Alignment.centerLeft,
child: Text('Furkan Akgün',
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
fontWeight: FontWeight.bold)),
),
],
),
),
),
],
),
SizedBox(
height: 20.0,
),
Row(
children: <Widget>[
Card(
color: Colors.grey[900],
margin: EdgeInsets.symmetric(horizontal: 10.0),
child: Icon(Icons.location_on),
),
Card(
color: Colors.grey[900],
margin:
EdgeInsets.symmetric(horizontal: 10.0, vertical: 7.0),
child: Container(
child: Column(
children: <Widget>[
Align(
alignment: Alignment.centerLeft,
child: Text('Ankara',
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
fontWeight: FontWeight.bold)),
),
],
),
),
),
],
),
SizedBox(
height: 20.0,
),
Row(
children: <Widget>[
Card(
color: Colors.grey[900],
margin: EdgeInsets.symmetric(horizontal: 10.0),
child: Icon(Icons.rate_review),
),
Card(
color: Colors.grey[900],
margin:
EdgeInsets.symmetric(horizontal: 10.0, vertical: 7.0),
child: Container(
child: SmoothStarRating(
spacing: 2.0,
allowHalfRating: true,
starCount: 5,
rating: 4.5,
size: 20,
color: Colors.yellow,
borderColor: Colors.white,
isReadOnly: true,
)),
),
],
),
SizedBox(
height: 20.0,
),
SizedBox(
height: 40.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
RaisedButton(
color: Colors.deepPurple[900],
onPressed: () {
//uploadPic(context);
},
elevation: 4.0,
splashColor: Colors.blueGrey,
child: Text(
'Edit',
style: TextStyle(color: Colors.white, fontSize: 16.0),
),
),
],
)
],
),
),
),
bottomNavigationBar: CircularBottomNavigation(
tabItems,
barBackgroundColor: Colors.deepPurple[900],
controller: _navigationController,
selectedCallback: (int selectedPos) {
if (selectedPos == 0) {
Navigator.pushNamed(context, 'dashboard_screen');
}
if (selectedPos == 2) {
Navigator.pushNamed(context, 'user_profile');
}
},
),
);
}
}
enter image description here
ERROR TYPE
Exception has occurred.
NoSuchMethodError (NoSuchMethodError: The getter 'uid' was called on null.
Receiver: null
Tried calling: uid)
My guess is that the error comes from this code in your build method:
FirebaseImage('gs://homeparty-68792.appspot.com/user_profile_images/${loggedInUser.uid}.png')
This is because the UI may be built before the user sign-in is completed.
To prevent this from happening you need to handle the fact that the user may not be signed in, in your build code too, for example by skipping the rendering of their profile image:
backgroundImage: loggedInUser != null ?
FirebaseImage('gs://homeparty-68792.appspot.com/user_profile_images/${loggedInUser.uid}.png') :
Text("Loading...")

Could not find the correct Provider<UserProvider> above this SignUp Widget

Error: Could not find the correct Provider above this SignUp Widget
To fix, please:
Ensure the Provider is an ancestor to this SignUp
Widget
Provide types to Provider
Provide types to Consumer
Provide types to Provider.of()
Ensure the correct context is being used.
class SignUp extends StatefulWidget {
#override
_SignUpState createState() => _SignUpState();
}
class _SignUpState extends State<SignUp> {
final _formKey = GlobalKey<FormState>();
final _key = GlobalKey<ScaffoldState>();
TextEditingController _email = TextEditingController();
TextEditingController _password = TextEditingController();
TextEditingController _name = TextEditingController();
bool hidePass = true;
#override
Widget build(BuildContext context) {
final user = Provider.of<UserProvider>(context);
return Scaffold(
key: _key,
body: user.status == Status.Authenticating ? Loading() : Stack(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(left:20, right:20.0, top: 80),
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(16),
boxShadow: [
BoxShadow(
color: Colors.grey[350],
blurRadius:
20.0, // has the effect of softening the shadow
)
],
),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(16.0),
child: Container(
alignment: Alignment.topCenter,
child: Image.asset(
'images/cart.png',
width: 120.0,
// height: 240.0,
)),
),
Padding(
padding:
const EdgeInsets.fromLTRB(14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(10.0),
color: Colors.grey.withOpacity(0.2),
elevation: 0.0,
child: Padding(
padding: const EdgeInsets.only(left: 12.0),
child: ListTile(
title: TextFormField(
controller: _name,
decoration: InputDecoration(
hintText: "Full name",
icon: Icon(Icons.person_outline),
border: InputBorder.none),
validator: (value) {
if (value.isEmpty) {
return "The name field cannot be empty";
}
return null;
},
),
),
),
),
),
Padding(
padding:
const EdgeInsets.fromLTRB(14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(10.0),
color: Colors.grey.withOpacity(0.2),
elevation: 0.0,
child: Padding(
padding: const EdgeInsets.only(left: 12.0),
child: ListTile(
title: TextFormField(
controller: _email,
decoration: InputDecoration(
hintText: "Email",
icon: Icon(Icons.alternate_email),
border: InputBorder.none),
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 'Please make sure your email address is valid';
else
return null;
}
return null;
},
),
),
),
),
),
Padding(
padding:
const EdgeInsets.fromLTRB(14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(10.0),
color: Colors.grey.withOpacity(0.2),
elevation: 0.0,
child: Padding(
padding: const EdgeInsets.only(left: 12.0),
child: ListTile(
title: TextFormField(
controller: _password,
obscureText: hidePass,
decoration: InputDecoration(
hintText: "Password",
icon: Icon(Icons.lock_outline),
border: InputBorder.none),
validator: (value) {
if (value.isEmpty) {
return "The password field cannot be empty";
} else if (value.length < 6) {
return "the password has to be at least 6 characters long";
}
return null;
},
),
trailing: IconButton(
icon: Icon(Icons.remove_red_eye),
onPressed: () {
setState(() {
hidePass = false;
});
}),
),
),
),
),
Padding(
padding:
const EdgeInsets.fromLTRB(14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(20.0),
color: deepOrange,
elevation: 0.0,
child: MaterialButton(
onPressed: () async{
if(_formKey.currentState.validate()){
if(!await user.signUp(_name.text ,_email.text, _password.text))
_key.currentState.showSnackBar(SnackBar(content: Text("Sign up failed")));
}
},
minWidth: MediaQuery.of(context).size.width,
child: Text(
"Sign up",
textAlign: TextAlign.center,
style: TextStyle(
color: white,
fontWeight: FontWeight.bold,
fontSize: 20.0),
),
)),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: InkWell(
onTap: () {
Navigator.pop(context);
},
child: Text(
"I already have an account",
textAlign: TextAlign.center,
style: TextStyle(color: deepOrange, fontSize: 16),
))),
Padding(
padding: const EdgeInsets.all(16.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Text("Or sign up with", style: TextStyle(fontSize: 18,color: Colors.grey),),
),
Padding(
padding:
const EdgeInsets.fromLTRB(14.0, 8.0, 14.0, 8.0),
child: Material(
child: MaterialButton(
onPressed: () async{
if(!await user.signUpWithGoogle())
_key.currentState.showSnackBar(SnackBar(content: Text("Sign in failed")));
},
child: Image.asset("assets/google-48.png", width: 30,)
)),
),
],
),
),
],
)),
),
),
],
),
);
}
}
keep getting error what am I doing wrong

Resources