简体   繁体   中英

How to verify user email usign Flutter and Firebase

I was following a guide on medium.com about this particular topic and created a class to manage auth stuff but it gives me an error.

import 'package:firebase_auth/firebase_auth.dart';
import 'package:lindo_app/models.dart/user.dart';


class AuthService {

  final FirebaseAuth _auth = FirebaseAuth.instance;

//auth change user stream

  Stream<User> get user {
    return _auth.onAuthStateChanged.map(_userFromFirebaseUser);
  }

//create user object

  User _userFromFirebaseUser(FirebaseUser user) {
    return (user != null) ? User(uid: user.uid) : null;
  }

  //Sign In with Email and Pass
  Future signInWithEmailAndPassword(String email, String password) async {
    try {
      AuthResult result = await _auth.signInWithEmailAndPassword(email: email, password: password);
      FirebaseUser user = result.user;
      return _userFromFirebaseUser(user);
    }
    catch(e){
      return null;
    }
  }

  //sign out
  Future signOut() async {
    try{
      return await _auth.signOut();
    }
    catch(error){
      print(error.toString(),);
      return null;
    }
  }

  // sign up

  Future signUp(String email, String password) async {
      FirebaseUser user = await _auth.createUserWithEmailAndPassword(email: email, password: password);
     try {
        await user.sendEmailVerification();
        return user.uid;
     } catch (e) {
        print("An error occured while trying to send email verification");
        print(e.message);
     }
  }
}

The error is:

AuthResult can't be assigned to FirebaseUser on line 47

(last method on the value of 'user' to be clear). Thanks in advance

The error is self-explanatory,you are assigning the returned value of createUserWithEmailAndPassword to a FirebaseUser variable while it returns an AuthResult

fix to your problem:

Future signUp(String email, String password) async {
      AuthResult result = await _auth.createUserWithEmailAndPassword(email: email, password: password);
     FirebaseUser user = result.user;
     //do something with user
     try {
        await user.sendEmailVerification();
        return user.uid;
     } catch (e) {
        print("An error occured while trying to send email verification");
        print(e.message);
     }
  }

AuthResult can't be assigned to FirebaseUser on line 47

You should call .user at the end of this line

 FirebaseUser user = await _auth.createUserWithEmailAndPassword(email: email, password: password).user;

instead of

FirebaseUser user = await _auth.createUserWithEmailAndPassword(email: email, password: password);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM