Problem in Flutter. Conflict between Firebase previous and last version Authentication - flutter

I am trying to make login and Signup features for my project but stuck in converting from Firebase old version to the new latest one. As I want to check if user signed in or not, I have added currentUser() method but then I got an error.
As I understand FirebaseUser class has replaced by AuthResult class
The main problem comes from currentUser() method: Error is the following and when I want to register, app shuts down;
(NoSuchMethodError: The getter 'uid' was called on null. Receiver: null Tried calling: uid)
This the old:
import 'dart:async';
import 'package:firebase_auth/firebase_auth.dart';
abstract class BaseAuth {
Future<String> signInWithEmailAndPassword(String email, String password);
Future<String> createUserWithEmailAndPassword(String email, String password);
Future<String> currentUser();
Future<void> signOut();
}
class Auth implements BaseAuth {
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
#override
Future<String> signInWithEmailAndPassword(String email, String password) async {
final FirebaseUser user = await _firebaseAuth.signInWithEmailAndPassword(email: email, password: password);
return user?.uid;
}
#override
Future<String> createUserWithEmailAndPassword(String email, String password) async {
final FirebaseUser user = await _firebaseAuth.createUserWithEmailAndPassword(email: email, password: password);
return user?.uid;
}
#override
Future<String> currentUser() async {
final FirebaseUser user = await _firebaseAuth.currentUser();
return user?.uid;
}
#override
Future<void> signOut() async {
return _firebaseAuth.signOut();
}
}
This is the new one:
abstract class BaseAuth{
Future<String> signInWithEmailAndPassword (String email, String password);
Future<String> createUserWithEmailAndPassword (String email, String password);
Future<String> currentUser();
}
class Auth implements BaseAuth{
#override
Future<String> signInWithEmailAndPassword (String email, String password) async {
final AuthResult user = await FirebaseAuth.instance
.signInWithEmailAndPassword(email: email, password: password);
return user.user.uid;
}
#override
Future<String> createUserWithEmailAndPassword (String email, String password) async {
final AuthResult user = await FirebaseAuth.instance
.createUserWithEmailAndPassword(email: email, password: password);
return user.user.uid;
}
#override
Future<String> currentUser() async {
final FirebaseUser user = await FirebaseAuth.instance.currentUser();
return user.uid; //Error comes from here
}
#override
Future<void> signOut() async {
return _firebaseAuth.signOut();
}
}

Related

Save authentication data to Firebase Realtime Database

I need the username and password that is created to be saved in the database, I have already created my database with realtime database that I am currently using to store data from a form that I create
import 'package:firebase_auth/firebase_auth.dart';
import 'dart:async';
import 'package:firebase_database/firebase_database.dart';
abstract class BaseAuth {
Future<String> singInWithEmailAndPassword(String email, String password);
Future<String> createUserWithEmailAndPassword(String email, String password);
Future<String> currentUser();
Future<void> singOut();
}
class Auth implements BaseAuth {
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
final databaseRef = FirebaseDatabase.instance.ref();
#override
Future<String> singInWithEmailAndPassword(
String email, String password) async {
UserCredential user = await _firebaseAuth.signInWithEmailAndPassword(
email: email.toString(), password: password.toString());
return user.toString();
}
#override
Future<String> createUserWithEmailAndPassword(
String email, String password) async {
UserCredential user = await _firebaseAuth.createUserWithEmailAndPassword(
email: email.toString(), password: password.toString());
return user.toString();
}
#override
Future<String> currentUser() async {
User currentUser = _firebaseAuth.currentUser!;
return currentUser.toString();
}
#override
Future<void> singOut() async {
return _firebaseAuth.signOut();
}
}
This es my auth.dart,this is where i created my methods to create and login
I hope you can support me since this is part of my final project

Firebase authentication in flutter

I am trying to set up Firebase Authentication for a login after setting up everything correctly I am running into an error in the dart file i created.
1- Undefined class 'FirebaseUser'
2.A value of type 'User' can't be returned from the method 'registerWithEmailAndPassword' because it has a return type of 'Future
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
class User {
final String uid;
User({required this.uid});
}
class AuthBase{
User _userFromFireBase (FirebaseUser user){
return User(uid: user.uid);
}
Future<void> registerWithEmailAndPassword(
String email, String password) async {
final authResult = await FirebaseAuth.instance
.createUserWithEmailAndPassword(email: email, password: password);
return _userFromFireBase(authResult.user);
}
}

Flutter : How to use Email Verification FIrebase Auth

I just finished Firebase Auth for my first application, but I want to add Email Verification when the user has Sign Up, please how can I make it.
class AuthServices {
final auth.FirebaseAuth _firebaseAuth = auth.FirebaseAuth.instance;
Login? _userFromFirebase(auth.User? user) {
if (user == null) {
return null;
}
return Login(user.uid, user.email);
}
Stream<Login?>? get user {
return _firebaseAuth.authStateChanges().map(_userFromFirebase);
}
Future<Login?> signUp(String email, String password, String name) async {
final credential = await _firebaseAuth.createUserWithEmailAndPassword(
email: email, password: password);
UserService().createUser(name);
return _userFromFirebase(credential.user);
}
Future<Login?> signIn(String email, String password) async {
final credential = await _firebaseAuth.signInWithEmailAndPassword(
email: email, password: password);
return _userFromFirebase(credential.user);
}
Future<void> signOut() async {
return await _firebaseAuth.signOut();
}
}
This will do your job:-
final firebaseUser = await FirebaseAuth.instance
.signInWithEmailAndPassword(email: email, password: password);
if (firebaseUser.isEmailVerified){
//Verified
}
else {
firebaseUser.sendEmailVerification();
}
Future<Login?> signUp(String email, String password, String name) async {
final credential = await _firebaseAuth.createUserWithEmailAndPassword(
email: email, password: password);
await credential.user?.sendEmailVerification(); // Add this line
UserService().createUser(name);
return _userFromFirebase(credential.user);
}

Flutter : Errors appearing after updating the Firebase auth package

I created the Firebase Auth class a year ago. Now After updating the Dart language and updating the firebase auth package some errors appeared.
import 'package:firebase_auth/firebase_auth.dart';
class AuthService {
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
Stream<String> get onAuthStateChanged => _firebaseAuth.onAuthStateChanged.map(
(FirebaseUser user) => user.uid,
);
// Sign up Email & passowrd
Future<String> createUserWithEmailAndPassword(
String email, String password, String name) async {
final currentUser = await _firebaseAuth.createUserWithEmailAndPassword(
email: email,
password: password,
);
//updat username
var userUpdateInfo = UserUpdateInfo();
userUpdateInfo.displayName = name;
await currentUser.updateProfile(userUpdateInfo);
await currentUser.reload();
return currentUser.uid;
}
// sign in Email & password
Future<String> sinInWithEmailAndPassword(
String email, String password) async {
return (await _firebaseAuth.signInWithEmailAndPassword(
email: email, password: password))
.uid;
}
// sign out
signOut() {
return _firebaseAuth.signOut();
}
}
click here to see error
All firebase plugins for flutter since a year ago have a lot of breaking changes you should go to firebase.flutter.dev and check it
I've been trying and searching for more than two weeks The error appears in the code:
//updat username
var userUpdateInfo = UserUpdateInfo();
userUpdateInfo.displayName = name;
await currentUser.updateProfile(userUpdateInfo);
await currentUser.reload();
return currentUser.uid;
}
The method 'UserUpdateInfo' isn't defined for the type 'AuthService'

UserProfile crashes after auth.getCurrentUser()

I am making an app in flutter an now when i try to show the user Name on the profile i got this error
════════ Exception caught by widgets library ═══════════════════════════════════
The following NoSuchMethodError was thrown building UserPage(dirty, dependencies: [MediaQuery], state: _UserProfile#ca57c):
The getter 'auth' was called on null.
Receiver: null
Tried calling: auth
The relevant error-causing widget was
UserPage
lib/HomePage.dart:92
When the exception was thrown, this was the stack
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
#1 _UserProfile.build
package:tariffo/UserPage.dart:131
#2 StatefulElement.build
package:flutter/…/widgets/framework.dart:4619
#3 ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:4502
#4 StatefulElement.performRebuild
package:flutter/…/widgets/framework.dart:4675
...
═══════════════════════════════════════════════════════════════════════════════
and i used this code
FutureBuilder(
future:
Provider.of(context).auth.getCurrentUser(),
builder: (context, snapshot) {
if (snapshot.connectionState ==
ConnectionState.done) {
return Text("${snapshot.data.displayName}",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 22,
));
} else {
return CircularProgressIndicator();
}
},
),
This is the code that i used for my auth.dart
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'User.dart';
String email, name, photoUrl;
class Authentication {
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
final GoogleSignIn _googleSignIn = GoogleSignIn();
Stream<String> get onAuthStateChanged => _firebaseAuth.onAuthStateChanged.map(
(FirebaseUser user) => user?.uid,
);
// GET UID
Future<String> getCurrentUID() async {
return (await _firebaseAuth.currentUser()).uid;
}
// GET CURRENT USER
Future getCurrentUser() async {
return await _firebaseAuth.currentUser();
}
// Email & Password Sign Up
Future<String> createUserWithEmailAndPassword(
String email, String password, String name) async {
final authResult = await _firebaseAuth.createUserWithEmailAndPassword(
email: email,
password: password,
);
// Update the username
await updateUserName(name, authResult.user);
return authResult.user.uid;
}
Future updateUserName(String name, FirebaseUser currentUser) async {
var userUpdateInfo = UserUpdateInfo();
userUpdateInfo.displayName = name;
await currentUser.updateProfile(userUpdateInfo);
await currentUser.reload();
}
// Email & Password Sign In
Future<String> signInWithEmailAndPassword(
String email, String password) async {
return (await _firebaseAuth.signInWithEmailAndPassword(
email: email, password: password))
.user
.uid;
}
// Sign Out
signOut() {
return _firebaseAuth.signOut();
}
// Reset Password
Future sendPasswordResetEmail(String email) async {
return _firebaseAuth.sendPasswordResetEmail(email: email);
}
// Create Anonymous User
Future singInAnonymously() {
return _firebaseAuth.signInAnonymously();
}
Future convertUserWithEmail(
String email, String password, String name) async {
final currentUser = await _firebaseAuth.currentUser();
final credential =
EmailAuthProvider.getCredential(email: email, password: password);
await currentUser.linkWithCredential(credential);
await updateUserName(name, currentUser);
}
Future convertWithGoogle() async {
final currentUser = await _firebaseAuth.currentUser();
final GoogleSignInAccount account = await _googleSignIn.signIn();
final GoogleSignInAuthentication _googleAuth = await account.authentication;
final AuthCredential credential = GoogleAuthProvider.getCredential(
idToken: _googleAuth.idToken,
accessToken: _googleAuth.accessToken,
);
await currentUser.linkWithCredential(credential);
await updateUserName(_googleSignIn.currentUser.displayName, currentUser);
}
// GOOGLE
Future<String> signInWithGoogle() async {
final GoogleSignInAccount account = await _googleSignIn.signIn();
final GoogleSignInAuthentication _googleAuth = await account.authentication;
final AuthCredential credential = GoogleAuthProvider.getCredential(
idToken: _googleAuth.idToken,
accessToken: _googleAuth.accessToken,
);
return (await _firebaseAuth.signInWithCredential(credential)).user.uid;
}
// APPLE
}
class NameValidator {
static String validate(String value) {
if (value.isEmpty) {
return "Name can't be empty";
}
if (value.length < 2) {
return "Name must be at least 2 characters long";
}
if (value.length > 50) {
return "Name must be less than 50 characters long";
}
return null;
}
}
class EmailValidator {
static String validate(String value) {
if (value.isEmpty) {
return "Email can't be empty";
}
return null;
}
}
class PasswordValidator {
static String validate(String value) {
if (value.isEmpty) {
return "Password can't be empty";
}
return null;
}
}
and this is the code for User.dart
import 'package:flutter/material.dart';
class User {
final String uid;
User({this.uid});
String adress;
bool business;
Map<String, dynamic> toJson() => {
'adress': adress,
'business': business,
};
}
Now it just appear a red background when i try to acces the profile page pressing the profile icon button
provider_widget.dart
import 'package:flutter/material.dart';
import 'auth.dart';
class Provider extends InheritedWidget {
final Authentication auth;
Provider({Key key, Widget child, this.auth}) : super(key: key, child: child);
#override
bool updateShouldNotify(InheritedWidget oldWidget) {
return true;
}
static Provider of(BuildContext context) =>
(context.inheritFromWidgetOfExactType(Provider) as Provider);
}