Search code examples
flutterflutter-dependenciesflutter-provider

Flutter Provider on logout


I'm making a chat app in Flutter and I went into an issue. I use provider package as State Management and I would like to display "Hi, NAME" in the AppBar where the user name is taken from a Firebase collection. So I created a refreshUser method in the user_provider.dart and I called him on the initState of the HomePage where the text "Hi, name" should appear. It works, however, I noticed that if i logout from my account and log in to another account, it displays the old account name. For example, if I'm logged to Alex account it shows "Hi, Alex", but if I logout and login to Steve's account, it still shows "Hi, Alex".

This is the code:

// UserProvider
 
class UserProvider with ChangeNotifier {
  UserModel _user = UserModel(uid: "", name: "", username: "", imageUrl: "");
 
  final FirestoreService _firestoreService = FirestoreService();
 
  UserModel get user => _user;
 
  Future<void> refreshUser() async {
    UserModel userModel = await _firestoreService.getUserInfo();
    _user = userModel;
    notifyListeners();
  }
}
 
// HomePage
class _HomePageState extends State<HomePage> {
  final _firestoreService = FirestoreService();
  final _authService = AuthService();
 
  @override
  void initState() {
    super.initState();
 
    SchedulerBinding.instance.addPostFrameCallback((_) async {
      await Provider.of<UserProvider>(context, listen: false).refreshUser();
    });
  }
 
  @override
  Widget build(BuildContext context) {
    var user = Provider.of<UserProvider>(context).user;
 
    return Scaffold(
      appBar: CustomAppBar(
        centerTitle: false,
        title: Text("Hi, ${user.name}"),
        leading: UserPic(user: user, radius: 30.0, withStatus: false,),
        leadingWidth: 30.0,
        actions: [
          IconButton(splashRadius: 15.0, onPressed: logOut, icon: const Icon(Icons.search_rounded))
        ],
      ),
    );
  }
}

about the main.dart, I use a StreamBuilder with Firebase authStateChanges as stream, and it automatically redirects to AuthPage() or HomePage()


Solution

  • add this function to UserProvider class

     void clearUserInfo() {
     _user =  UserModel(uid: "", name: "", username: "", imageUrl: ""); 
     notifyListeners();
    
     }
    

    then remove Future keyword from refreshUser() to be like

    void refreshUser()async{....};
    

    then add this lines before user variable inside the build function

    context.read<UserProvider>().clearUserInfo();
    
    context.read<UserProvider>().refreshUser();
    

    if it still doesn't work change this line

    var user = Provider.of<UserProvider>(context).user;
    

    to this

    var user = context.watch<UserProvider>();
    

    i hope this fix it if not let me know please