issue with flutter firebase login - firebase

I recently made things work with the login/register module on my app but there are 2 things that are not working:
first when I register it's ok, I can see in my Firebase Console that the app is creating a new user so that's fine. However, when I try to log in with a user that doesn't exist it still makes me go to the homepage.
no idea how to make a persistent login, like someone who log in and someone who register when they close the app and then restart the app they should be able to keep the login and then logout if they want.
CAN ANYBODY HELP??
I leave here the code:
MAIN
import 'package:flutter/material.dart';
import 'package:sport_app/auth_screen.dart';
import 'package:sport_app/home_screen.dart';
import 'package:sport_app/intro_screen.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
inputDecorationTheme: InputDecorationTheme(
filled: true,
fillColor: Color(0xfff2f9fe),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.grey[200]),
borderRadius: BorderRadius.circular(25),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.grey[200]),
borderRadius: BorderRadius.circular(25),
),
disabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.grey[200]),
borderRadius: BorderRadius.circular(25),
),
),
),
home: IntroScreen(),
routes: {
'intro': (context) => IntroScreen(),
'home': (context) => HomeScreen(),
'login': (context) => AuthScreen(authType: AuthType.login),
'register': (context) => AuthScreen(authType: AuthType.register),
},
);
}
}
AUTH_PAGE
import 'package:flutter/material.dart';
import 'package:sport_app/auth_screen.dart';
import 'package:sport_app/auth.dart';
import 'package:sport_app/original_button.dart';
class AuthForm extends StatefulWidget {
final AuthType authType;
const AuthForm({Key key, #required this.authType}) : super(key: key);
#override
_AuthFormState createState() => _AuthFormState();
}
class _AuthFormState extends State<AuthForm> {
final _formKey = GlobalKey<FormState>();
String _email = '', _password = '';
AuthBase authBase = AuthBase();
#override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 50, vertical: 20),
child: Column(
children: <Widget>[
TextFormField(
decoration: InputDecoration(
labelText: 'Enter your email',
hintText: 'ex: test#gmail.com',
),
onChanged: (value) {
_email = value;
},
validator: (value) =>
value.isEmpty ? 'You must enter a valid email' : null,
),
SizedBox(height: 10),
TextFormField(
decoration: InputDecoration(
labelText: 'Enter your password',
),
obscureText: true,
onChanged: (value) {
_password = value;
},
validator: (value) => value.length <= 6
? 'Your password must be larger than 6 characters'
: null,
),
SizedBox(height: 20),
OriginalButton(
text: widget.authType == AuthType.login ? 'Login' : 'Register',
color: Colors.lightBlue,
textColor: Colors.white,
onPressed: () async {
if (_formKey.currentState.validate()) {
if (widget.authType == AuthType.login) {
await authBase.loginWithEmailAndPassword(_email, _password);
Navigator.of(context).pushReplacementNamed('home');
} else {
await authBase.registerWithEmailAndPassword(_email, _password);
Navigator.of(context).pushReplacementNamed('home');
}
// print(_email);
// print(_password);
}
},
),
SizedBox(height: 6),
FlatButton(
onPressed: () {
if (widget.authType == AuthType.login) {
Navigator.of(context).pushReplacementNamed('register');
print(widget.authType);
} else {
Navigator.of(context).pushReplacementNamed('login');
}
},
child: Text(
widget.authType == AuthType.login
? 'Don\'t have an account?'
: 'Already have an account?',
style: TextStyle(fontSize: 18, color: Colors.black54),
),
),
],
),
),
);
}
}
AUTHBASE
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
class User {
final String uid;
User({#required this.uid});
}
class AuthBase {
User _userFromFirebase(FirebaseUser user) {
return user != null ? User(uid: user.uid) : null;
}
Future<void> registerWithEmailAndPassword(
String email, String password) async {
try {
final authResult = await FirebaseAuth.instance
.createUserWithEmailAndPassword(email: email, password: password);
return _userFromFirebase(authResult.user);
} catch (e) {
print(e.toString());
return null;
}
}
Future<void> loginWithEmailAndPassword(String email, String password) async {
try {
final authResult = await FirebaseAuth.instance
.signInWithEmailAndPassword(email: email, password: password);
return _userFromFirebase(authResult.user);
} catch (e) {
print(e.toString());
return null;
}
}
Future<void> logout() async {
await FirebaseAuth.instance.signOut();
}
}

UPDATE
You simply navigate to the homepage, even when the login has not completed successfully, becaus there is no condition logic. Do the navigation only in your authBase class, then you should be fine.
You need to import the FirebaseAuthException before you can use it. Then, you
Future<bool> loginWithEmailAndPassword(String email, String password) async {
try {
final authResult = await FirebaseAuth.instance
.signInWithEmailAndPassword(email: email, password: password);
if(authResult.user != null) { Navigator.of(context).pushReplacementNamed('home'); }
} on FirebaseAuthException catch (e) {
print(e.toString());
if(e.code == 'wrong-password') { Scaffold.of(context).showSnackBar(SnackBar(
content: Text("Wrong Password"),
)); }
else if (e.code == 'user-not-found') { Scaffold.of(context).showSnackBar(SnackBar(
content: Text("User not found"),
)); }
else if (e.code == 'invalid-email') { Scaffold.of(context).showSnackBar(SnackBar(
content: Text("Invalid E-Mail"),
)); }
return false;
}
}
and remove change your widget code to:
if (_formKey.currentState.validate()) {
if (widget.authType == AuthType.login) {
await authBase.loginWithEmailAndPassword(_email, _password);
} else {
await authBase.registerWithEmailAndPassword(_email, _password);
}
}
Second Problem:
You could try storing the login credentials in the storage (user flutter_secure_storage package for encryption) after the first login and then retrieve it on App startup to perform login like above
Here is a link for the package you should use to store the credentials
flutter_secure_storage

Related

my flutter firebase app always have same error

I have made a online store app with flutter and backend on firebase , in sign up page whenever click on create account button it says same error, no matter if I put data on Text Fields or not, I am really confused about this!
the error is
given String is empty or null
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../widgets/custom_button.dart';
import '../widgets/custom_input.dart';
import 'const.dart';
import 'login.dart';
class SingUP extends StatefulWidget {
SingUP({Key? key}) : super(key: key);
#override
State<SingUP> createState() => _SingUPState();
}
class _SingUPState extends State<SingUP> {
Future<void> advanceAlertDialog(String message) {
return Get.defaultDialog(
title: 'Invalid Input',
content: Text(message),
actions: [
ElevatedButton(
onPressed: () => Get.back(),
child: Text('OK !'),
)
],
contentPadding: EdgeInsets.all(15.0),
);
}
Future<String?> signInMethod() async {
try {
await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: takeEmail, password: takePassword);
return 'ok';
} on FirebaseAuthException catch (error) {
if (error.code == 'weak-password') {
return 'the password is too week';
} else if (error.code == 'email-already-in-use') {
return 'The account with this email is already exist !';
}
return error.message;
} catch (error) {
return error.toString();
}
}
void signIn() async {
setState(() {
isLoading = true;
});
String? result = await signInMethod();
if (result != 'ok') {
advanceAlertDialog(result!);
setState(() {
isLoading = false;
});
} else {
setState(() {
isLoading = false;
});
Get.to(LoginPage());
Get.snackbar('Successful', 'Account Created !',
backgroundColor: Colors.greenAccent, icon: Icon(Icons.check_circle));
}
}
bool isLoading = false;
String takeEmail = '';
String takePassword = '';
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
width: double.infinity,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
padding: EdgeInsets.only(top: 50),
child: Text(
'Create a New Account !',
style: Constans.headingTextStyle,
textAlign: TextAlign.center,
),
),
Column(
children: [
CustomInput(
hintText: 'Enter Your Email ...',
onChanged: (value) {
takeEmail = value;
},
checkPassword: false,
),
CustomInput(
hintText: 'Enter Your Password ...',
onChanged: (value) {
takeEmail = value;
},
checkPassword: true,
),
CustomButton(
text: 'Create Account',
loading: isLoading,
onTap: () {
signIn();
},
mode: false,
)
],
),
CustomButton(
text: 'Back to Login',
onTap: () => Get.back(),
mode: true,
loading: isLoading,
)
],
),
),
);
}
}
Emain and password widgets are the same takeEmail = value;, change the password onChange value to takePassword = value;, also where is exactly the error thrown?. I advice to add breakpoints to signInMethod() to see the input values of email: takeEmail, password: takePassword (both of this strings) and after the on FirebaseAuthException catch (error) { to see if the error is thrown from firebase or is in your code.

set a username & profile picture firebase login and then get it for a profile later on

ok, its late and I can't quite figure this out for some reason. I am coming from swift and newer to flutter. my code is below, I can't get my username to register in my json or anything else and I can't figure out how to pull it out later either, any help would be appreciated, I can pull out all the data but I haven't figured out how to assign the displayName or profile picture on a later screen
class WelcomeScreen extends StatefulWidget {
const WelcomeScreen({Key? key}) : super(key: key);
static const String id = 'welcome_screen';
#override
_WelcomeScreenState createState() => _WelcomeScreenState();
}
class _WelcomeScreenState extends State<WelcomeScreen> with SingleTickerProviderStateMixin{
FirebaseAuth auth = FirebaseAuth.instance;
final _auth = FirebaseAuth.instance;
var _isLoading = false;
late AnimationController controller;
late Animation animation;
void _completeLogin() {
Navigator.pushReplacement<void, void>(
context,
MaterialPageRoute<void>(
builder: (BuildContext context) => Home(),
),
);
}
void _submitAuthForm(
String email,
String username,
String password,
File imageFile,
bool isLogin,
BuildContext ctx,
) async {
UserCredential authResult;
try {
setState(() {
_isLoading = true;
});
if (isLogin) {
authResult = await _auth.signInWithEmailAndPassword(
email: email,
password: password,
);
print('$username');
} else {
authResult = await _auth.createUserWithEmailAndPassword(
email: email,
password: password,
);
print('$username');
final ref = FirebaseStorage.instance
.ref()
.child('user_image')
.child(authResult.user!.uid + 'jpg');
await ref.putFile(imageFile);
final url = await ref.getDownloadURL();
await FirebaseFirestore.instance
.collection('users')
.doc(authResult.user!.uid)
.set({
'username': username,
'email': email,
'image_url': url,
});
}
} on FirebaseAuthException catch (error) {
var message = 'An error occurred, please check your credentials!';
if (error.message != null) {
message = error.message!;
}
ScaffoldMessenger.of(ctx).showSnackBar(SnackBar(content: Text(message)));
setState(() {
_isLoading = false;
});
}
}
#override
void initState() {
super.initState();
controller =
AnimationController (
duration: Duration(seconds: 1),
vsync: this,
);
animation = ColorTween(begin: Colors.transparent, end: Colors.white.withOpacity(0.5)).animate(controller);
controller.forward();
controller.addListener(() {
setState(() {
});
});
}
#override
Widget build(BuildContext context) {
FirebaseAuth.instance
.authStateChanges()
.listen((User? user) {
if (user == null) {
print('User is currently signed out!');
} else {
_completeLogin();
print('1');
}
});
return Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("images/bar1.jpg"),
fit: BoxFit.fill,
)
),
child: Scaffold(
backgroundColor: Colors.white.withOpacity(0.5),
body: Container(
child: Center(
child: SingleChildScrollView(
child: Column(
children: <Widget>[
Image.asset('assets/images/logo.png'),
AuthForm(
_submitAuthForm,
_isLoading,
),
],
),
),
),
),
),
);
}
}
and here is my auth form
FocusNode myFocusNode = FocusNode();
class AuthForm extends StatefulWidget {
const AuthForm(this.submitFn, this.isLoading, {Key? key}) : super(key: key);
final bool isLoading;
final void Function(
String email,
String userName,
String password,
File image,
bool isLogin,
BuildContext ctx,
) submitFn;
#override
_AuthFormState createState() => _AuthFormState();
}
class _AuthFormState extends State<AuthForm> {
final _formKey = GlobalKey<FormState>();
var _isLogin = true;
String _userEmail = '';
String _userName = '';
String _userPassword = '';
File _userImageFile = File('');
void _pickedImage(File image) {
_userImageFile = image;
}
void _trySubmit() {
final isValid = _formKey.currentState!.validate();
FocusScope.of(context).unfocus();
if (_userImageFile.path.isEmpty && !_isLogin) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Please pick an image'),
),
);
return;
}
if (isValid) {
_formKey.currentState!.save();
widget.submitFn(
_userEmail.trim(),
_userName.trim(),
_userPassword.trim(),
_userImageFile,
_isLogin,
context,
);
}
}
#override
Widget build(BuildContext context) {
return Center(
child: Card(
margin: const EdgeInsets.symmetric(horizontal: 30, vertical: 20),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
child: AnimatedContainer(
duration: const Duration(milliseconds: 350),
curve: Curves.easeIn,
constraints: BoxConstraints(
minHeight: _isLogin ? 224 : 390,
maxHeight: _isLogin ? 268 : 456,
),
child: Form(
key: _formKey,
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
if (!_isLogin)
UserImagePicker(_pickedImage),
TextFormField(
cursorColor: Colors.red,
key: const ValueKey('email'),
autocorrect: false,
textCapitalization: TextCapitalization.none,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
labelText: 'Email address',
),
validator: (val) {
if (EmailValidator.validate(val!) == false) {
return 'Please enter a valid email address.';
}
return null;
},
onSaved: (val) {
_userEmail = val!;
},
),
if (!_isLogin)
TextFormField(
cursorColor: Colors.red,
key: const ValueKey('username'),
decoration: const InputDecoration(
labelText: 'Username',
),
validator: (val) {
if (val!.isEmpty || val.length < 4) {
return 'Username must be at least 4 characters.';
}
return null;
},
onSaved: (val) {
_userName = val!;
},
),
TextFormField(
cursorColor: Colors.red,
key: const ValueKey('password'),
decoration: const InputDecoration(
labelText: 'Password',
),
obscureText: true,
validator: (val) {
if (val!.isEmpty || val.length < 6) {
return 'Check your password, it must be 6 character or longer.';
}
return null;
},
onSaved: (val) {
_userPassword = val!;
},
),
const SizedBox(height: 12),
widget.isLoading
? const CircularProgressIndicator()
: ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.red),
),
child: Text(_isLogin ? 'Log in' : 'Sign up'),
onPressed: _trySubmit,
),
TextButton(
child: Text(_isLogin
? 'Create new account'
: 'I already have an account'),
onPressed: () {
setState(() {
_isLogin = !_isLogin;
});
},
),
if (_isLogin)
TextButton(
child: Text(
'Forgot Password?'
),
onPressed: () {
Navigator.pushNamed(context, ForgotPassword.id);
},
),
],
),
),
),
),
),
),
);
}
}
answered it my self by writing to a category in firebase then used the below code to pull it out later
import 'package:flutter/material.dart';
// Import the firebase_core and cloud_firestore plugin
import 'package:firebase_core/firebase_core.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class AddUser extends StatelessWidget {
final String fullName;
final String company;
final int age;
AddUser(this.fullName, this.company, this.age);
#override
Widget build(BuildContext context) {
// Create a CollectionReference called users that references the firestore collection
CollectionReference users = FirebaseFirestore.instance.collection('users');
Future<void> addUser() {
// Call the user's CollectionReference to add a new user
return users
.add({
'full_name': fullName, // John Doe
'company': company, // Stokes and Sons
'age': age // 42
})
.then((value) => print("User Added"))
.catchError((error) => print("Failed to add user: $error"));
}
return TextButton(
onPressed: addUser,
child: Text(
"Add User",
),
);
}
}
and this code to query it
class GetUserName extends StatelessWidget {
final String documentId;
GetUserName(this.documentId);
#override
Widget build(BuildContext context) {
CollectionReference users = FirebaseFirestore.instance.collection('users');
return FutureBuilder<DocumentSnapshot>(
future: users.doc(documentId).get(),
builder:
(BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (snapshot.hasError) {
return Text("Something went wrong");
}
if (snapshot.hasData && !snapshot.data!.exists) {
return Text("Document does not exist");
}
if (snapshot.connectionState == ConnectionState.done) {
Map<String, dynamic> data = snapshot.data!.data() as Map<String, dynamic>;
return Text("Full Name: ${data['full_name']} ${data['last_name']}");
}
return Text("loading");
},
);
}
}
You can pass them as a constructor
Example
class UserDetail extends StatelessWidget {
final File image;
final String display;
UserDetail({Key key, required this.image, required this.display}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(child:Row(
children: <Widget>[
Image.file(image: File(image))),
Text(display),
], ),);
}
}
You can read Passing data between screens in Flutter
For more info.

How to solve SnackBar did not work and black screen in flutter after add StreamBuilder

I am doing login and sign up using firebase. I have two error. First is the error message from firebase that did not show at the snack bar. The second is after I add StreamBuilder my apps become black screen.
Does anyone know how to solve this question? Thanks in advance.
Here is the code:
Main.dart
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (ctx, userSnapshot) {
if (userSnapshot.hasData) {
return HomePage();
}
return AuthScreen();
}),
);
}
}
AuthScreen.dart
class AuthScreen extends StatefulWidget {
#override
_AuthScreenState createState() => _AuthScreenState();
}
class _AuthScreenState extends State<AuthScreen> {
final _auth = FirebaseAuth.instance;
var _isLoading = false;
void _submitAuthForm(
String email,
String password,
String username,
bool isLogin,
BuildContext ctx,
) async {
UserCredential authResult;
try {
setState(() {
_isLoading = true;
});
if (isLogin) {
authResult = await _auth.signInWithEmailAndPassword(
email: email,
password: password,
);
} else {
authResult = await _auth.createUserWithEmailAndPassword(
email: email,
password: password,
);
await FirebaseFirestore.instance
.collection('users')
.doc(authResult.user.uid)
.set({
'username': username,
'email': email,
});
}
} on PlatformException catch (err) {
var message = 'An error occurred, pelase check your credentials!';
if (err.message != null) {
message = err.message;
}
ScaffoldMessenger.of(ctx).showSnackBar(
SnackBar(
content: Text(message),
backgroundColor: Theme.of(ctx).errorColor,
),
);
setState(() {
_isLoading = false;
});
} catch (err) {
print(err);
setState(() {
_isLoading = false;
});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).primaryColor,
body: AuthForm(
_submitAuthForm,
_isLoading,
),
);
}
}
Auth_form.dart
class AuthForm extends StatefulWidget {
AuthForm(
this.submitFn,
this.isLoading,
);
final bool isLoading;
final void Function(
String email,
String password,
String userName,
bool isLogin,
BuildContext ctx,
) submitFn;
#override
_AuthFormState createState() => _AuthFormState();
}
class _AuthFormState extends State<AuthForm> {
final _formKey = GlobalKey<FormState>();
var _isLogin = true;
var _userEmail = '';
var _userName = '';
var _userPassword = '';
void _trySubmit() {
final isValid = _formKey.currentState.validate();
FocusScope.of(context).unfocus();
if (isValid) {
_formKey.currentState.save();
widget.submitFn(_userEmail.trim(), _userPassword.trim(), _userName.trim(),
_isLogin, context);
}
}
#override
Widget build(BuildContext context) {
return Center(
child: Card(
margin: EdgeInsets.all(20),
child: SingleChildScrollView(
child: Padding(
padding: EdgeInsets.all(16),
child: Form(
key: _formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
TextFormField(
key: ValueKey('email'),
validator: (value) {
if (value.isEmpty || !value.contains('#')) {
return 'Please enter a valid email address.';
}
return null;
},
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
labelText: 'Email address',
),
onSaved: (value) {
_userEmail = value;
},
),
if (!_isLogin)
TextFormField(
key: ValueKey('username'),
validator: (value) {
if (value.isEmpty || value.length < 4) {
return 'Please enter at least 4 characters';
}
return null;
},
decoration: InputDecoration(labelText: 'Username'),
onSaved: (value) {
_userName = value;
},
),
TextFormField(
key: ValueKey('password'),
validator: (value) {
if (value.isEmpty || value.length < 7) {
return 'Password must be at least 7 characters long.';
}
return null;
},
decoration: InputDecoration(labelText: 'Password'),
obscureText: true,
onSaved: (value) {
_userPassword = value;
},
),
SizedBox(height: 12),
if (widget.isLoading) CircularProgressIndicator(),
if (!widget.isLoading)
RaisedButton(
child: Text(_isLogin ? 'Login' : 'Signup'),
onPressed: _trySubmit,
),
if (!widget.isLoading)
FlatButton(
textColor: Theme.of(context).primaryColor,
child: Text(_isLogin
? 'Create new account'
: 'I already have an account'),
onPressed: () {
setState(() {
_isLogin = !_isLogin;
});
},
)
],
),
),
),
),
),
);
}
}
home.dart
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
#override
Widget build(BuildContext context) {
return Container();
}
}
To show a SnackBar first define a key:
final key = GlobalKey<ScaffoldMessengerState>();
Then, add a ScaffoldMessenger to your widget tree:
ScaffoldMessenger(
key: key, // assign the key property to your previously created key
child: Scaffold(...),
)
Now you can show the SnackBar:
key.currentState.showSnackBar(SnackBar(...))
Please add code for your home page, so we can inspect it and see why it shows a black screen, you probably forgot to wrap it in a Scaffold. You should return a Scaffold in the home page and the black screen will go away.

How do i catch error of authentication while logging in and signup using firebase and flutter?

I am pretty new to flutter and this is my first project in which i am using backend like firebase.
So i pre build an ui and started to integrate firebase in it it was successfully done and it is working as accepted but when i am trying to print out the errors while logging in signup i am failing to do that, i am able to catch the errors in my console but i wait to update my users with that error text.
when ever i am trying to log in though i am providing a wrong password it is taking me to the home page which i dont want
This is my Log In page with a pre build ui and with working setup of log in
import 'package:flutter/material.dart';
import 'package:notepad/Authentigation%20Screens/signUp.dart';
import 'package:notepad/animation/bouncypagetrans.dart';
import 'package:notepad/animation/fadeanimation.dart';
import 'package:notepad/auth/authMethod.dart';
import 'package:notepad/screens/homepage.dart';
import 'package:notepad/widgets/VxTextsHeaders.dart';
import 'package:notepad/widgets/customRaisedButton.dart';
import 'package:notepad/widgets/loading.dart';
import 'package:notepad/widgets/textformField.dart';
import 'ForgotPassword.dart';
class LogIn extends StatefulWidget {
#override
_LogInState createState() => _LogInState();
}
class _LogInState extends State<LogIn> {
String error;
AuthMethods authMethods = new AuthMethods();
bool isLoading = false;
final formKey = GlobalKey<FormState>();
TextEditingController emailTextEditingController =
new TextEditingController();
TextEditingController passwordTextEditingController =
new TextEditingController();
logMein() {
if (formKey.currentState.validate()) {
try {
setState(() {
isLoading = true;
});
authMethods
.signInWithEmailAndPassword(emailTextEditingController.text,
passwordTextEditingController.text)
.then((val) {
// print("${val.uId}");
Navigator.pushReplacement(
context,
BouncyPageRout(
widget: HomePage(),
),
);
});
} catch (e) {
setState(() {
error = e.message;
});
}
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomPadding: true,
body: isLoading
? Loading()
: SafeArea(
child: Container(
width: double.infinity,
padding: EdgeInsets.fromLTRB(30.0, 100.0, 30.0, 20.0),
height: MediaQuery.of(context).size.height,
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
FadeAnimation(
1.0,
headerTitle("Hello,"),
),
FadeAnimation(
2.0,
headerSubTitle("Log in to continue"),
),
],
),
SizedBox(height: 65),
Column(
children: [
Form(
key: formKey,
child: Column(children: [
SizedBox(height: 20),
FadeAnimation(
3.0,
buildTextField(
validator: (val) {
return val.isEmpty ||
RegExp(r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+#[a-zA-Z0-9]+\.[a-zA-Z]+")
.hasMatch(val)
? null
: "Please provide a valid Email";
},
labelText: "Email",
controller: emailTextEditingController),
),
SizedBox(height: 20),
FadeAnimation(
3.5,
buildTextField(
validator: (val) {
return val.isEmpty || val.length < 6
? "Please Provide a Strong Password,/n Provide somthing greater than 6 "
: null;
},
labelText: "Password",
obscureText: true,
controller:
passwordTextEditingController),
),
])),
SizedBox(height: 10.0),
Container(
alignment: Alignment.centerRight,
child: FadeAnimation(
4.0,
InkWell(
onTap: () {
Navigator.push(
context,
BouncyPageRout(
widget: ForgotPassword(),
),
);
},
child: Text(
'Forgot Password?',
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.deepOrange,
fontSize: 14),
),
),
),
),
SizedBox(height: 40),
FadeAnimation(
4.5,
raisedButton(
context: context,
onPressed: () {
logMein();
},
color: Colors.deepOrange,
title: "Log In",
textColor: Colors.white,
),
),
SizedBox(
height: 20.0,
),
FadeAnimation(
5.0,
raisedButton(
context: context,
onPressed: () {
Navigator.push(
context,
BouncyPageRout(
widget: SignUp(),
),
);
},
color: Colors.white,
title: "SignUp"),
),
],
)
],
),
),
),
),
);
}
}
AuthMethods page with contains all the codes of firebase
import 'package:notepad/auth/user.dart';
class AuthMethods {
String error;
final FirebaseAuth _auth = FirebaseAuth.instance;
User _userFromFirebaseUser(FirebaseUser user) {
return user != null ? User(userId: user.uid) : null;
}
Future signInWithEmailAndPassword(String email, String password) async {
try {
AuthResult result = await _auth.signInWithEmailAndPassword(
email: email, password: password);
FirebaseUser firebaseUser = result.user;
return _userFromFirebaseUser(firebaseUser);
} catch (e) {
print(e.toString());
}
}
Future signUpwithEmailAndPassword(String email, String password) async {
try {
AuthResult result = await _auth.createUserWithEmailAndPassword(
email: email, password: password);
FirebaseUser firebaseUser = result.user;
return _userFromFirebaseUser(firebaseUser);
} catch (e) {
print(e.toString());
}
}
Future resetPass(String email) async {
try {
return await _auth.sendPasswordResetEmail(email: email);
} catch (e) {
print(e.toString());
}
}
Future signOut() async {
try {
return await _auth.signOut();
} catch (e) {
print(e.toString());
}
}
}
so basically i want to notify my users a valid error message and untill they solve that they should not navigate to a perticular screen
You can use a snackbar widget and call them in your throw function! Follow this link to learn more about snackbars
https://flutter.dev/docs/cookbook/design/snackbars

flutter firebase google sign out not working

I'm trying to implement google sign in/ sign out, but my sign out's not working. I get an error signOut() was called on null. When I print out user after the user signs in, I do get all the proper information, but when I print out in my signout function, it says it's null. Custom firebase user does work. Here's my auth.dart file:
import 'dart:async';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
abstract class BaseAuth {
Future<String> signIn(String email, String password);
Future<String> signUp(String email, String password);
Future<FirebaseUser> getCurrentUser();
Future<void> sendEmailVerification();
Future<void> signOut();
Future<bool> isEmailVerified();
Future<String> signInWithGoogle();
}
class Auth implements BaseAuth {
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
final GoogleSignIn googleSignIn = GoogleSignIn();
FirebaseUser user;
Future<String> signIn(String email, String password) async {
user = (await _firebaseAuth.signInWithEmailAndPassword(email: email, password: password)).user;
return user.email;
}
Future<String> signUp(String email, String password) async {
FirebaseUser user = (await _firebaseAuth.createUserWithEmailAndPassword(
email: email, password: password)).user;
return user.uid;
}
Future<FirebaseUser> getCurrentUser() async {
user = await _firebaseAuth.currentUser();
return user;
}
signOut() async {
//print("signed in user: ${authService.user}");
await _firebaseAuth.signOut();
}
Future<void> sendEmailVerification() async {
FirebaseUser user = await _firebaseAuth.currentUser();
user.sendEmailVerification();
}
Future<bool> isEmailVerified() async {
FirebaseUser user = await _firebaseAuth.currentUser();
return user.isEmailVerified;
}
Future<String> signInWithGoogle() async {
final GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn();
final GoogleSignInAuthentication googleSignInAuthentication =
await googleSignInAccount.authentication;
final AuthCredential credential = GoogleAuthProvider.getCredential(
accessToken: googleSignInAuthentication.accessToken,
idToken: googleSignInAuthentication.idToken,
);
user = (await _firebaseAuth.signInWithCredential(credential)).user;
assert(!user.isAnonymous);
assert(await user.getIdToken() != null);
final FirebaseUser currentUser = await _firebaseAuth.currentUser();
assert(user.uid == currentUser.uid);
return 'signInWithGoogle succeeded: $user';
}
}
Something else strange is if I boot up the app and am already logged in (as google), i hit signout and it appears to work. Nothing in my console, but it goes back to login screen. Then if I log back in as google and signout, error starts happening. Another weird thing is if I happened to already be logged in and I get it to log out after one click, without changing anything if I restart my app in android studio it takes me back to the screen where I'm supposedly already logged in. This is only happening on Google Sign Out (not firebase log out).
Any idea what I might be doing wrong? Thanks
pubspec.yaml
dependencies:
firebase_auth: ^0.14.0+5
firebase_database: ^3.0.7
google_sign_in: ^4.0.7
firebase_storage:
image_picker:
cloud_firestore:
shared_preferences:
fluttertoast:
cached_network_image:
intl:
one page where I use it: (I have many, but implemented similar to this and it doesn't work in any of my pages)
import 'package:flutter/material.dart';
import 'package:pet_helper/chat.dart';
import 'package:pet_helper/lost_and_found.dart';
import 'package:pet_helper/pet_adoption.dart';
import 'authentication.dart';
class HomePage extends StatefulWidget {
HomePage({Key key, this.auth, this.userId, this.onSignedOut})
: super(key: key);
final BaseAuth auth;
final VoidCallback onSignedOut;
final String userId;
#override
State<StatefulWidget> createState() => new _HomePageState();
}
class _HomePageState extends State<HomePage> {
final GlobalKey<FormState> formKey = GlobalKey<FormState>();
int _currentIndex = 0;
#override
void initState() {
super.initState();
}
final List<Widget> _children = [
new LostAndFoundPage(),
new PetAdoptionPage(),
new ChatPage(),
];
_signOut() async {
try {
await widget.auth.signOut();
widget.onSignedOut();
} catch (e) {
print(e);
}
}
onTabTapped(int index) {
setState(() {
_currentIndex = index;
});
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
automaticallyImplyLeading:false,
title: new Text('Pet Helper'),
actions: <Widget>[
new FlatButton(
child: new Text('Logout',
style: new TextStyle(fontSize: 17.0, color: Colors.white)),
onPressed: _signOut)
],
),
body: _children[_currentIndex], // new
bottomNavigationBar: BottomNavigationBar(
onTap: onTabTapped, // new
currentIndex: _currentIndex, // new
items: [
new BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text('Lost & Found'),
),
new BottomNavigationBarItem(
icon: Icon(Icons.pets),
title: Text('Pet Adoption'),
),
new BottomNavigationBarItem(
icon: Icon(Icons.person), title: Text('Chat'))
],
));
}
}
and for completion, here's my login page:
import 'package:flutter/material.dart';
import 'package:pet_helper/home_page.dart';
import 'authentication.dart';
class LoginSignUpPage extends StatefulWidget {
LoginSignUpPage({this.auth, this.onSignedIn});
final BaseAuth auth;
final VoidCallback onSignedIn;
#override
State<StatefulWidget> createState() => new _LoginSignUpPageState();
}
enum FormMode { LOGIN, SIGNUP }
class _LoginSignUpPageState extends State<LoginSignUpPage> {
final _formKey = new GlobalKey<FormState>();
String _email;
String _password;
String _errorMessage;
// Initial form is login form
FormMode _formMode = FormMode.LOGIN;
bool _isIos;
bool _isLoading;
// Check if form is valid before perform login or signup
bool _validateAndSave() {
final form = _formKey.currentState;
if (form.validate()) {
form.save();
return true;
}
return false;
}
// Perform login or signup
void _validateAndSubmit() async {
setState(() {
_errorMessage = "";
_isLoading = true;
});
if (_validateAndSave()) {
String userId = "";
try {
if (_formMode == FormMode.LOGIN) {
userId = await widget.auth.signIn(_email, _password);
print('Signed in: $userId');
} else {
userId = await widget.auth.signUp(_email, _password);
widget.auth.sendEmailVerification();
_showVerifyEmailSentDialog();
print('Signed up user: $userId');
}
setState(() {
_isLoading = false;
});
if (userId.length > 0 && userId != null && _formMode == FormMode.LOGIN) {
widget.onSignedIn();
}
} catch (e) {
print('Error: $e');
setState(() {
_isLoading = false;
if (_isIos) {
_errorMessage = e.details;
} else
_errorMessage = 'Incorrect user or password';
});
}
}
}
#override
void initState() {
_errorMessage = "";
_isLoading = false;
super.initState();
}
void _changeFormToSignUp() {
_formKey.currentState.reset();
_errorMessage = "";
setState(() {
_formMode = FormMode.SIGNUP;
});
}
void _changeFormToLogin() {
_formKey.currentState.reset();
_errorMessage = "";
setState(() {
_formMode = FormMode.LOGIN;
});
}
#override
Widget build(BuildContext context) {
_isIos = Theme.of(context).platform == TargetPlatform.iOS;
return new Scaffold(
appBar: new AppBar(
title: new Text('Pet Helper'),
),
body: Stack(
children: <Widget>[
_showBody(),
_showCircularProgress(),
],
));
}
Widget _showCircularProgress(){
if (_isLoading) {
return Center(child: CircularProgressIndicator());
} return Container(height: 0.0, width: 0.0,);
}
void _showVerifyEmailSentDialog() {
showDialog(
context: context,
builder: (BuildContext context) {
// return object of type Dialog
return AlertDialog(
title: new Text("Verify your account"),
content: new Text("Link to verify account has been sent to your email"),
actions: <Widget>[
new FlatButton(
child: new Text("Dismiss"),
onPressed: () {
_changeFormToLogin();
Navigator.of(context).pop();
},
),
],
);
},
);
}
Widget _showBody(){
return new Container(
padding: EdgeInsets.all(16.0),
child: new Form(
key: _formKey,
child: new ListView(
shrinkWrap: true,
children: <Widget>[
_showLogo(),
_showEmailInput(),
_showPasswordInput(),
_showErrorMessage(),
_showPrimaryButton(),
_showSecondaryButton(),
_googleSignInButton(),
],
),
));
}
Widget _showErrorMessage() {
if (_errorMessage.length > 0 && _errorMessage != null) {
return new Text(
_errorMessage,
style: TextStyle(
fontSize: 13.0,
color: Colors.red,
height: 1.0,
fontWeight: FontWeight.w300),
);
} else {
return new Container(
height: 0.0,
);
}
}
Widget _showLogo() {
return new Hero(
tag: 'hero',
child: Padding(
padding: EdgeInsets.fromLTRB(0.0, 30.0, 0.0, 0.0),
child: CircleAvatar(
backgroundColor: Colors.transparent,
radius: 120.0,
child: Image.asset('assets/babies.png'),
),
),
);
}
Widget _showEmailInput() {
return Padding(
padding: const EdgeInsets.fromLTRB(0.0, 25.0, 0.0, 0.0),
child: new TextFormField(
maxLines: 1,
keyboardType: TextInputType.emailAddress,
autofocus: false,
decoration: new InputDecoration(
hintText: 'Email',
icon: new Icon(
Icons.mail,
color: Colors.grey,
)),
validator: (String value) {
if (value.isEmpty) {
_isLoading = false;
return 'Email can\'t be empty';
}
else{
return null;
}
},
onSaved: (value) => _email = value.trim(),
),
);
}
Widget _showPasswordInput() {
return Padding(
padding: const EdgeInsets.fromLTRB(0.0, 15.0, 0.0, 0.0),
child: new TextFormField(
maxLines: 1,
obscureText: true,
autofocus: false,
decoration: new InputDecoration(
hintText: 'Password',
icon: new Icon(
Icons.lock,
color: Colors.grey,
)),
validator: (String value) {
if (value.isEmpty) {
_isLoading = false;
return 'Password can\'t be empty';
}
else{
return null;
}
},
onSaved: (value) => _password = value.trim(),
),
);
}
Widget _showSecondaryButton() {
return new FlatButton(
child: _formMode == FormMode.LOGIN
? new Text('Create an account',
style: new TextStyle(fontSize: 18.0, fontWeight: FontWeight.w300))
: new Text('Have an account? Sign in',
style:
new TextStyle(fontSize: 18.0, fontWeight: FontWeight.w300)),
onPressed: _formMode == FormMode.LOGIN
? _changeFormToSignUp
: _changeFormToLogin,
);
}
Widget _showPrimaryButton() {
return new Padding(
padding: EdgeInsets.fromLTRB(0.0, 35.0, 0.0, 0.0),
child: SizedBox(
height: 40.0,
child: new RaisedButton(
elevation: 5.0,
shape: new RoundedRectangleBorder(borderRadius: new BorderRadius.circular(30.0)),
color: Colors.blue,
child: _formMode == FormMode.LOGIN
? new Text('Login',
style: new TextStyle(fontSize: 20.0, color: Colors.white))
: new Text('Create account',
style: new TextStyle(fontSize: 20.0, color: Colors.white)),
onPressed: _validateAndSubmit,
),
));
}
void submitGoogleLogin() async{
setState(() {
_errorMessage = "";
_isLoading = true;
});
String userId = "";
userId = await widget.auth.signInWithGoogle().whenComplete(() {
widget.onSignedIn();
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return new HomePage();
},
),
);
});
print('Signed in: $userId');
}
Widget _googleSignInButton() {
return OutlineButton(
splashColor: Colors.grey,
onPressed: submitGoogleLogin,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(40)),
highlightElevation: 0,
borderSide: BorderSide(color: Colors.grey),
child: Padding(
padding: const EdgeInsets.fromLTRB(0, 10, 0, 10),
child: Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image(image: AssetImage("assets/google_logo.png"), height: 30.0),
Padding(
padding: const EdgeInsets.only(left: 10),
child: Text(
'Sign in with Google',
style: TextStyle(
fontSize: 15,
color: Colors.grey,
),
),
)
],
),
),
);
}
}
Oh and root page changes the state of the user:
import 'package:flutter/material.dart';
import 'login_signup_page.dart';
import 'authentication.dart';
import 'home_page.dart';
class RootPage extends StatefulWidget {
RootPage({this.auth});
final BaseAuth auth;
#override
State<StatefulWidget> createState() => new _RootPageState();
}
enum AuthStatus {
NOT_DETERMINED,
NOT_LOGGED_IN,
LOGGED_IN,
}
class _RootPageState extends State<RootPage> {
AuthStatus authStatus = AuthStatus.NOT_DETERMINED;
String _userId = "";
#override
void initState() {
super.initState();
widget.auth.getCurrentUser().then((user) {
setState(() {
if (user != null) {
_userId = user?.uid;
}
authStatus =
user?.uid == null ? AuthStatus.NOT_LOGGED_IN : AuthStatus.LOGGED_IN;
});
});
}
void _onLoggedIn() {
widget.auth.getCurrentUser().then((user){
setState(() {
_userId = user.uid.toString();
});
});
setState(() {
authStatus = AuthStatus.LOGGED_IN;
});
}
void _onSignedOut() {
setState(() {
authStatus = AuthStatus.NOT_LOGGED_IN;
_userId = "";
});
}
Widget _buildWaitingScreen() {
return Scaffold(
body: Container(
alignment: Alignment.center,
child: CircularProgressIndicator(),
),
);
}
#override
Widget build(BuildContext context) {
switch (authStatus) {
case AuthStatus.NOT_DETERMINED:
return _buildWaitingScreen();
break;
case AuthStatus.NOT_LOGGED_IN:
return new LoginSignUpPage(
auth: widget.auth,
onSignedIn: _onLoggedIn,
);
break;
case AuthStatus.LOGGED_IN:
if (_userId.length > 0 && _userId != null) {
return new HomePage(
userId: _userId,
auth: widget.auth,
onSignedOut: _onSignedOut,
);
} else return _buildWaitingScreen();
break;
default:
return _buildWaitingScreen();
}
}
}
initializing root page
Main.dart
void main() async{
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Pet Helper',
debugShowCheckedModeBanner: false,
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new RootPage(auth: new Auth()));
}
}
abstract class BaseAuth {
Future<String> signIn(String email, String password);
Future<String> signUp(String email, String password);
Future<FirebaseUser> getCurrentUser();
Future<void> sendEmailVerification();
Future<void> signOut();
Future<bool> isEmailVerified();
Future<String> signInWithGoogle();
void signOutGoogle();
}
class Auth implements BaseAuth {
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
final GoogleSignIn googleSignIn = GoogleSignIn();
FirebaseUser user;
Future<String> signIn(String email, String password) async {
user = (await _firebaseAuth.signInWithEmailAndPassword(email: email, password: password)).user;
return user.email;
}
Future<String> signUp(String email, String password) async {
FirebaseUser user = (await _firebaseAuth.createUserWithEmailAndPassword(
email: email, password: password)).user;
return user.uid;
}
Future<FirebaseUser> getCurrentUser() async {
user = await _firebaseAuth.currentUser();
return user;
}
signOut() async {
print("signed in user: $user");
await _firebaseAuth.signOut();
}
Future<void> sendEmailVerification() async {
FirebaseUser user = await _firebaseAuth.currentUser();
user.sendEmailVerification();
}
Future<bool> isEmailVerified() async {
FirebaseUser user = await _firebaseAuth.currentUser();
return user.isEmailVerified;
}
Future<String> signInWithGoogle() async {
final GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn();
final GoogleSignInAuthentication googleSignInAuthentication =
await googleSignInAccount.authentication;
final AuthCredential credential = GoogleAuthProvider.getCredential(
accessToken: googleSignInAuthentication.accessToken,
idToken: googleSignInAuthentication.idToken,
);
user = (await _firebaseAuth.signInWithCredential(credential)).user;
assert(!user.isAnonymous);
assert(await user.getIdToken() != null);
final FirebaseUser currentUser = await _firebaseAuth.currentUser();
assert(user.uid == currentUser.uid);
return 'signInWithGoogle succeeded: $user';
}
}
final Auth authService = Auth(); // add this to the bottom outside the class
Using a global variable
So let me explain. Each time you call Auth(), it creates a new instance of that class. So in one instance, you might sign the user in. In another instance, you might sign the user out. The variables will contain different values for the variables. So if you use a different instance for signing users out than you did for signing them in, the user variable will be null, therefore not allowing you to sign them out and printing null.
Solution
The solution is a global variable to access the Auth class once. Ex. var authService = Auth();
Put the variable outside the Auth class so it can be accessed in any class, anywhere
Thanks everyone for you answers and support. I found the problem. When signing in google, widget.onSignedIn redirects me to home page (it's in root page). I was redirecting to homepage in the google sign in button after calling on SignedIn which is how I was losing the scope of the user variable. Thanks everyone!
in my case I was getting the Error:"Null check operator used on null value" whenever I call the signout function through the button which was wraped with GetBuilder.
so the solution was that I had to initiate the controller before I call it like:
GetBuilder<LoginController>(
init: LoginController(),// **I was missing this part**
builder: (controller) {
return Column(...)});

Resources