gpt4 book ai didi

firebase - 使用 Flutter ChangeNotifierProvider 进行身份验证

转载 作者:行者123 更新时间:2023-12-03 02:59:13 27 4
gpt4 key购买 nike

我正在使用 ChangeNotifierProvider 来处理我的 Flutter 应用的应用状态。

我的 main.dart 文件

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:flutter_app/services/auth.dart';

Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider<AuthService>(
create: (context) => AuthService(), // initializes auth.dart file here
child: MaterialApp(
initialRoute: '/',
onGenerateRoute: RouteGenerator.generateRoute,
debugShowCheckedModeBanner: false,
title: '...',
home: WelcomeScreen(),
));
}
}

我正在尝试更改 auth.dart 中的 uid 字段的值

auth.dart 文件

import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';

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

String uid = ""; //initial value of uid

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

Stream<UserM> get user {
return null;
}

Future signInWithEmail(String email, String password) async {
try {
UserCredential result = await _auth.signInWithEmailAndPassword(
email: email, password: password);
User user = result.user;
uid = user.uid; //trying to change uid here
print('user id: $uid'); //new value is printed here
notifyListeners();
return _userFromFirebaseUser(user);
} catch (e) {
print(e.toString());
return null;
}
}

uid 改变了,但是当我试图在另一个文件中获取新值时,我仍然得到旧值,即在顶部声明的空字符串。这就是我尝试访问它的方式

final auth = Provider.of<AuthService>(context, listen: true).uid;
print(auth);

请问我做错了什么?

最佳答案

我不明白为什么需要使用 Provider 来获取 Firebase 中用户的 uid。您可以通过执行 currentUser.uid 同步获取 uid
这是一个例子:

print(FirebaseAuth.instance.currentUser.uid);

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

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