使用 Flutter ChangeNotifierProvider 进行身份验证

Using Flutter ChangeNotifierProvider for authentication

我正在使用 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);