Using Flutter ChangeNotifierProvider for authentication

327

I don't get why there is a need to use Provider to get the uid of a user in Firebase. You can get the uid synchronously by doing currentUser.uid.
Here is an example:

print(FirebaseAuth.instance.currentUser.uid);
Share:
327
emmaakachukwu
Author by

emmaakachukwu

Updated on December 24, 2022

Comments

  • emmaakachukwu
    emmaakachukwu over 1 year

    I am using ChangeNotifierProvider to handle app state for my flutter app.

    My main.dart file

    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(),
            ));
      }
    }
    

    I am trying to change the value of the uid field here in auth.dart

    auth.dart file

    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 changes but then when i try to get the new value in another file, i still get the old value which is the empty string declared on top. This is how i am trying to access it

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

    What am I doing wrong please?