gpt4 book ai didi

firebase - 使用 Provider flutter 对 Firebase 进行身份验证

转载 作者:行者123 更新时间:2023-12-04 09:46:32 24 4
gpt4 key购买 nike

我试图实现这个认证 here Firebase with Povider 问题是我想保存变量 logined 的状态,即使我关闭并重新启动应用程序,所以我使用了此代码但不起作用

    class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Consumer<AuthenticationService>(builder: (_, auth, __) {
if (auth.getCurrentUser() != null)
return HomeView();
else
return TermsView();
});
}
}

这里获取当前用户的方法
Future getCurrentUser() async {
FirebaseUser _user ;
_user = await FirebaseAuth.instance.currentUser();

return _user ;
}

有没有办法检查登录内部 Consumer ?

最佳答案

您需要使用 FirebaseAuth.currentUser要检查用户是否已登录,我正在使用 FutureBuilderConsumer对于这项工作。

void main() {
WidgetsFlutterBinding.ensureInitialized();

runApp(
ChangeNotifierProvider<Auth>(
create: (_) => Auth(),
child: MaterialApp(home: MyApp()),
),
);
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Consumer<Auth>(
builder: (_, auth, __) {
return FutureBuilder<FirebaseUser>(
future: auth.currentUser,
builder: (context, snapshot) {
if (snapshot.hasData) return HomeScreen();
return LoginScreen();
},
);
},
);
}
}

class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color(0xFF4C3E13),
appBar: AppBar(title: Text('Home Screen')),
floatingActionButton: FloatingActionButton.extended(
label: Text('Sign out'),
onPressed: () async {
final auth = Provider.of<Auth>(context, listen: false);
await auth.signOut();
},
),
);
}
}

class LoginScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Login Screen')),
body: Center(
child: RaisedButton(
onPressed: () async {
final auth = Provider.of<Auth>(context, listen: false);
await auth.signIn(email: 'user@user.com', password: 'user1234');
},
child: Text('Sign In'),
),
),
);
}
}

class Auth with ChangeNotifier {
final _auth = FirebaseAuth.instance;

Future<void> signOut() async {
await _auth.signOut();
notifyListeners();
}

Future<void> signIn({@required String email, @required String password}) async {
await _auth.signInWithEmailAndPassword(email: email, password: password);
notifyListeners();
}

Future<FirebaseUser> get currentUser async {
return await _auth.currentUser();
}
}

关于firebase - 使用 Provider flutter 对 Firebase 进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62085806/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com