问题描述
我正在使用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。您可以通过执行uid
来同步获取currentUser.uid
。
这是一个示例:
print(FirebaseAuth.instance.currentUser.uid);