用于管理Firebase身份验证的StreamController

时间:2020-03-28 17:12:07

标签: firebase flutter dart firebase-authentication

我在以下Firebase登录流程上遇到了麻烦。我创建了一个StreamController来主要侦听Firebase的OnAuthStateChanged流,并向该流添加了一个数据点(一个用户对象,其中包含我从Firestore中获取的其他数据)。我的位置是在我的应用程序中的其他地方收听StreamController的流,以获取用户的完整信息。

我的AuthService类:

import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:dispatch/models/user.dart';
import 'package:firebase_auth/firebase_auth.dart';

class AuthService {
  static FirebaseAuth _auth = FirebaseAuth.instance;
  static Firestore _dbReference = Firestore.instance;
  final authStreamController = setStreamController();

  // create User, we will need to fetch more information from Firestore in the future
  Future<User> _userFromFirebaseUser(FirebaseUser user) async {
    //return user != null ? User(uid:user.uid) : null;
    return user != null ? (await _getUserDetailsAsync(User(uid:user.uid))) : null;
  }

  // get user details data
  Future<User> _getUserDetailsAsync(User user) async {
    try {
      QuerySnapshot querySnapshot = await _dbReference.collection('user-details')
        .where('auth_id', isEqualTo: user.uid)
        .getDocuments();
      Map<String, dynamic> userInfo = querySnapshot.documents.first.data;
      user.email = userInfo['email'] != null ? userInfo['email'] : null;
      user.firstName = userInfo['first_name'] != null ? userInfo['first_name'] : null;
      user.lastName = userInfo['last_name'] != null ? userInfo['last_name'] : null;
      return user;
    } catch(e) {
      print(e.toString());
      return null;
    }
  }

  // define a stream controller with the OnAuthStateChanged stream as its stream
  static StreamController<User> setStreamController(){
    StreamController<User> authStreamController = StreamController();
    Stream<User> _stream = _auth.onAuthStateChanged.map((FirebaseUser user) => User(uid: user.uid));
    authStreamController.addStream(_stream);
    return authStreamController;
  }

  // expose stream controller via a getter
  StreamController<User> get streamControllerGetter {
    return authStreamController;
  }

  // sign with email and password
  Future signInWithUserAndPassword(String email, String password) async {
    try {
      AuthResult result = await _auth.signInWithEmailAndPassword(email: email, password: password);
      FirebaseUser user = result.user;
      // fetch the user's details from Cloud Firestore
      // return final user
      User appUser = await _userFromFirebaseUser(user);
      authStreamController.sink.add(appUser);
      return appUser;
    } catch(e) {
      print(e.toString());
      return null;
    }
  }

  // sign out
  Future signOut() async {
    try {
      return await _auth.signOut();
    } catch(e) {
      print('Sign out failed:');
      print(e.toString());
      return null;
    }
  } 
}

MyApp类

class MyApp extends StatelessWidget {
    // wrap MaterialApp widget with Provider
    return StreamProvider<User>.value(
          //listening to the user change stream
          value: AuthService().streamControllerGetter.stream,
          child: MaterialApp(
            title: 'Flutter Demo',
            theme: ThemeData(
              primarySwatch: Colors.blue,
            ),
            home: LoginWrapper(),
          ),
    );
  }

由于某种原因,这整个过程都不​​起作用,我似乎没有收到添加到StreamController接收器中的最后一个User对象。有什么想法吗?

0 个答案:

没有答案