Im trying to use firebase for my flutter apps, and its seem there is an error in my code , i know firebaseuser need to change to user, but its seem it does not work , please help me , im new.
import 'package:firebase_auth/firebase_auth.dart';
import 'package:quizmaker/view/signin.dart';
import 'package:quizmaker/models/user.dart';
class AuthService {
FirebaseAuth _auth = FirebaseAuth.instance;
Future signInEmailAndPass(String email, String password) async {
try {
UserCredential userCredential = await _auth.signInWithEmailAndPassword(
email: email, password: password);
User user = authResult.user; //the error is in this part
} catch (e) {
print(e.toString());
}
}
}
In this code snippet:
UserCredential userCredential = await _auth.signInWithEmailAndPassword(
email: email, password: password);
User user = authResult.user;
You're trying to use an authResult variable that is never defined. My best guess is that you want to get the user from the userCredential instead, so:
UserCredential userCredential = await _auth.signInWithEmailAndPassword(
email: email, password: password);
User user = userCredential.user;
This still won't work though, since userCredential.user may be null, and is thus defined as User? and not User. Since you're using await, you can be certain that there is a user, so you can do:
User user = userCredential.user!;
Related
I'm trying to get the uid, but it always returns the uid of the previously created account.
createUserWithEmailAndPassword does not execute the login after being completed.
So it should be returning the uid correctly, right?
Below are 2 pictures of the database and Authentication, as well as the code.
Future _singUp() async {
final User? user = auth.currentUser;
final uid = user!.uid;
try {
await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: _emailController.text,
password: _passwordController.text,
);
await FirebaseFirestore.instance.collection('users').add({
'email': _emailController.text,
'name': _nameController.text,
'Id_usuario': uid
});
} on FirebaseAuthException catch (e) {
_handleSingUpError(e);
}
}
When you use createUserWithEmailAndPassword it will return a UserCredential as a result, you can use that to update your user variable, so in code it would be something like this:
UserCredential result = await FirebaseAuth.instance.createUserWithEmailAndPassword(email: email, password: password);
User? user = result.user;
I am working on a application with flutter and firebase and i am working on the auth for user and i want tu use the function uid but it's dont work, why ?
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
class FirebaseHelper {
//Authentification
final auth = FirebaseAuth.instance;
Future<UserCredential> handleSignIn(String mail, String password) async{
final UserCredential user = await auth.signInWithEmailAndPassword(email: mail, password: password);
return user;
}
Future<UserCredential> handleCreate(String mail, String password, String prenom, String nom) async{
final UserCredential user = await FirebaseAuth.instance.createUserWithEmailAndPassword(email: mail, password: password);
String uid = user.uid;
Map<String, String> map = {
"prenom" : prenom,
"nom" : nom,
};
addUser(uid, map);
return user;
}
//database
static final base = FirebaseDatabase.instance.reference();
// ignore: non_constant_identifier_names
final base_user = base.child("users");
addUser(String id, Map map){
base_user.child(uid).set(map);
}
}
it's mark The getter 'uid' isn't defined for the type 'UserCredential'. and Undefined name 'uid'. I dont know what I can do... please help me
In cases like this, I find it really helpful to keep the reference documentation for handy. In there, you can see that UserCredential indeed does not have a uid property, which explains the error message. If we browser a bit further, you'll notice that a credentials has a user property, which in turn has a uid.
So
final UserCredential credential = await FirebaseAuth.instance.createUserWithEmailAndPassword(email: mail, password: password);
String uid = credential.user.uid; // or credential.user?.uid if you're using null-safety
I'm a bit new to this, but I'm confused about how to access a user's Google username when signing in with Google. I used Lit Firebase Auth so that basically I have to just say
context.signInWithGoogle();
But I need a display name as in my database when a user signed up with email they could enter a username, by which the text they entered would be stored and then later display as their username.
Here is my register.dart
try {
await Firebase.initializeApp();
UserCredential user = await FirebaseAuth.instance
.createUserWithEmailAndPassword(
email: _emailController.text,
password: _passwordController.text,
);
User updateUser = FirebaseAuth.instance.currentUser;
updateUser.updateProfile(
displayName: _usernameController.text);
userSetup(_usernameController.text);
Navigator.of(context).pushAndRemoveUntil(
HomeScreen.route, (route) => false);
}
And the important part is the
userSetup
Which from my database will take that text and update the displayName.
So I guess I'm asking what to fill userSetup() instead of _usernameController.text in the case of Google sign in.
You can try out the following code for the google signing in flutter and getting credential from google and use them to firebase and the variable user contain all the user information like email, imageurl and name.
GoogleSignIn _googleSignIn = new GoogleSignIn();
GoogleSignInAccount googleSignInAccount = await _googleSignIn.signIn();
GoogleSignInAuthentication googleSignInAuthentication = await googleSignInAccount.authentication;
AuthCredential credential = GoogleAuthProvider.credential(idToken: googleSignInAuthentication.idToken, accessToken: googleSignInAuthentication.accessToken);
var result = (await _auth.signInWithCredential(credential));
_user = result.user;
With a phpMySQL background, I'm a little bit lost.
I've successfully created a registration process with Flutter and Firebase Auth (simple email/password method) following a tutorial.
I would like add a "username" and "age" field to the registration form.
In Firebase I've created a database called "users", and in it a String typed "userid" that's blank. But is it even necessary? What do I do next? How is it mapped to the User UID in the authentication table? How do I push it and retrieve it with Flutter?
I've explored this post to no avail Add extra User Information with firebase
If that helps, my authentication file contains this:
class Auth implements BaseAuth {
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
Future<String> signIn(String email, String password) async {
FirebaseUser user = await _firebaseAuth.signInWithEmailAndPassword(
email: email, password: password);
return user.uid;
}
Future<String> signUp(String email, String password) async {
FirebaseUser user = await _firebaseAuth.createUserWithEmailAndPassword(
email: email, password: password);
return user.uid;
}
Have tried this:
Future<String> signUp(String email, String password) async {
FirebaseUser user = await _firebaseAuth.createUserWithEmailAndPassword(
email: email, password: password);
Firestore.instance.collection('users').document().setData({ 'userid': user.uid, 'displayName': 'bobby' });
return user.uid;
}
But it throws an error:
5.17.0 - [Firebase/Firestore][I-FST000001] Write at users/-L_6e1CFkU1YchxsSPay failed: Missing or insufficient permissions.
Ok seems the above is all good.
Just had to change the Database rules from false to true as per the below post:
https://stackoverflow.com/a/46925637/3475894
First time implementing Firebase Auth, also new to Flutter dev, and I'm looking to use email and passwords, not Google sign-in. The only examples I see of Firebase Auth being used are anonymously or with Google. Is there a resource / tutorial that shows how to properly set up the calls with the signInWithEmailAndPassword method?
Many thanks!
In my app I have an auth class because I don't like to litter my widget classes with non-widget code, but you can plop this code inside your widget class if you want.
In auth.dart I have:
import 'package:firebase_auth/firebase_auth.dart';
class Auth {
final FirebaseAuth auth = FirebaseAuth.instance;
Future<User> handleSignInEmail(String email, String password) async {
UserCredential result =
await auth.signInWithEmailAndPassword(email: email, password: password);
final User user = result.user!;
return user;
}
Future<User> handleSignUp(email, password) async {
UserCredential result = await auth.createUserWithEmailAndPassword(
email: email, password: password);
final User user = result.user!;
return user;
}
}
Then in my login/register screen I create an instance of my auth class:
var authHandler = new Auth();
Finally, in my login buttons onPressed callback I have:
onPressed: () {
authHandler.handleSignInEmail(emailController.text, passwordController.text)
.then((FirebaseUser user) {
Navigator.push(context, new MaterialPageRoute(builder: (context) => new HomePage()));
}).catchError((e) => print(e));
}
Here is one example from my service. I ask for the email, name and password fields.
registerWithEmail(String name, String email, String password) async {
First I check if the email is already registered with facebook or something.
List<String> providers = await firebaseAuth.fetchProvidersForEmail(email: email);
This is not ideal solution, but you want to handle if the user is already registered, and than link email with current user
if (providers != null && providers.length > 0) {
print("already has providers: ${providers.toString()}");
return handleProviders(providers);
}
Create new User
FirebaseUser newUser = await firebaseAuth.createUserWithEmailAndPassword(email: email, password: password);
await newUser.sendEmailVerification();
This is basically it. I update the name filed of the user, since I have it.
var userUpdateInfo = new UserUpdateInfo();
userUpdateInfo.displayName = name;
await firebaseAuth.updateProfile(userUpdateInfo);
await newUser.reload();
And later You can save the user inside your firestore, where user uid is document ID. So I can get it later.
Git repo with full explanation example for Email/Password Sign in Firebase using flutter
This may help you.
Git Repo: https://github.com/myvsparth/firebase_email_signin
Full Article Step by Step: https://www.c-sharpcorner.com/article/how-to-do-simple-login-with-email-id-in-flutter-using-google-firebase/
This code is for register new user
fb_auth.UserCredential userCredential = await fb_auth
.FirebaseAuth.instance
.createUserWithEmailAndPassword(email: email, password: password);
And this is for login previous user
fb_auth.UserCredential userCredential = await fb_auth
.FirebaseAuth.instance
.signInWithEmailAndPassword(email: email, password: password)
And that fb_auth is
import 'package:firebase_auth/firebase_auth.dart' as fb_auth;