xpetta
xpetta

Reputation: 718

Flutter Firebase: I want to stream the details of the logged in user across the app using Stream provider

I'm getting the below error:

The return type 'AuthUser?' isn't a 'User?', as required by the closure's context.

From the below code:

class AuthService {
  final FirebaseAuth authInstance = FirebaseAuth.instance;
  final FirebaseFirestore firestoreInstance = FirebaseFirestore.instance;

  Stream<User?> get currentUser => authInstance.authStateChanges().map(
        (User? firebaseUser) => (firebaseUser != null) ? AuthUser.fromFirebaseUser(user: firebaseUser) : null,
      );
}

Below is the code for the model class:

import 'package:firebase_auth/firebase_auth.dart';

class AuthUser {
  String? uid;
  String? email;
  String? userName;

  AuthUser({
    required this.uid,
    required this.email,
    required this.userName,
  });

  AuthUser.fromFirebaseUser({User? user}) {
    uid = user!.uid;
    email = user.email;
    userName = user.displayName;
  }
}

I would also like to know how to consume this stream using the StreamProvider<AuthUser>.value.

Are either of Consumer widget or the Provider.of(context) widget appropriate to access the values?

Upvotes: 3

Views: 1030

Answers (2)

Victor Eronmosele
Victor Eronmosele

Reputation: 7706

Your stream is mapping the User model from Firebase to your AuthUser model. So you need to change the return type of the currentUser getter.

Change this:

Stream<User?> get currentUser => authInstance.authStateChanges().map(
        (User? firebaseUser) => (firebaseUser != null) ? AuthUser.fromFirebaseUser(user: firebaseUser) : null,
);

to this:

Stream<AuthUser?> get currentUser => authInstance.authStateChanges().map(
        (User? firebaseUser) => (firebaseUser != null) ? AuthUser.fromFirebaseUser(user: firebaseUser) : null,
);

Upvotes: 4

Gbenga B Ayannuga
Gbenga B Ayannuga

Reputation: 2792

Auth have is own storage that store all this information all you need is to is to declear a global users then asses the infomation any place in the app...

example

User users

then example of authentication

final googleUser = await googleSignIn.signIn();
      final googleAuth = await googleUser.authentication;
      final AuthCredential credential = GoogleAuthProvider.credential(
        accessToken: googleAuth?.accessToken,
        idToken: googleAuth?.idToken,
      );
      users = (await auth.signInWithCredential(credential)).user;
      if (users == null) {
        return false;
      }
      return true;
    } catch (e) {
      print('this is error .......$e');
      return null;
    }

Upvotes: -1

Related Questions