在Flutter中使用StreamProvider 4.0.3从Firebase监控身份验证状态

时间:2020-04-23 16:54:01

标签: firebase flutter firebase-authentication provider

如果用户未明确退出应用,我正在尝试自动登录。我正在使用Firebase进行身份验证,并使用pub的提供程序包来监视auth状态的更改。

我有一个服务dart文件(最初来自TheNetNin​​ja教程),该文件公开了一个流,并用流提供程序包装了main.dart文件。

class FoodMart extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
  return StreamProvider(
    create: (_) => AuthService().user,
    child: MaterialApp(
      title: 'Flutter Demo',
      onGenerateRoute: Router.generateRoute,
      home: Landing(),
    ),
  );
}
}

我已关闭并重新打开该应用程序,但仍未重定向到主页。我做错了吗?当我热重载时,我将被重定向到主页,但只有那时。 这是AuthService.dart类的实现:

import 'dart:async';

import 'package:firebase_auth/firebase_auth.dart';
import 'package:food_mart/models/users.dart';
import 'package:food_mart/services/database.dart';

class AuthService {

FirebaseAuth _mAuth = FirebaseAuth.instance;

Stream<User> get user {
  return _mAuth.onAuthStateChanged.map(_mapUserFromFirebase);
}

User _mapUserFromFirebase(FirebaseUser firebaseUser) {
  return firebaseUser != null ? User(userId: firebaseUser.uid) : null;
}

Future createUser(String email, String pwd, String role) async{
  try {
    AuthResult result = await _mAuth.createUserWithEmailAndPassword(email: email, password: pwd);
    FirebaseUser firebaseUser = result.user;

    await DatabaseService(userId: firebaseUser.uid).setUserData(email: email, role: role);
    return _mapUserFromFirebase(firebaseUser);
  } catch(e){
    print(e.toString());
    return e;
  }
}

Future loginUser(String email, String pwd) async{
  try {
    AuthResult authResult = await _mAuth.signInWithEmailAndPassword(email: email, password: pwd);
    FirebaseUser firebaseUser = authResult.user;
    return _mapUserFromFirebase(firebaseUser);
  } catch(e){
    print(e.toString());
    return null;
  }
}

Future signOut() async {
  try {
    return await _mAuth.signOut();
  } catch(e){
    print(e.toString());
    return null;
  }
}

}

为简洁起见,省略了用户模型。请帮忙 :) 预先谢谢你!

0 个答案:

没有答案