How to properly call FirebaseFirestore.instance.clearPersistence() in Flutter?

Viewed 1841

I'm facing the same problem as this guy question

But his accepted answer didn't helped me.

The problem:

When an user signs out, and another different user signs in, all data shown on my app is from the previous signed out user due to firebase caching system. I searched about this issue and found a solution that consists in calling this method:

FirebaseFirestore.instance.clearPersistence();

But everytime and everywhere I place this line of code, throws an exception saying I cannot call this method when the client is running:

Exception has occurred. PlatformException (PlatformException(failed-precondition, Operation was rejected because the system is not in a state required for the operation's execution. If performing a query, ensure it has been indexed via the Firebase console., {code: failed-precondition, message: Operation was rejected because the system is not in a state required for the operation's execution. If performing a query, ensure it has been indexed via the Firebase console., nativeErrorMessage: Persistence cannot be cleared while the client is running., nativeErrorCode: 9}))

so, how to call this method? or better, is there a best way to solve this problem?

3 Answers

It seems it's necessary to terminate the FirebaseFirestore.instance first.

At the end of my log off method I call:

await FirebaseFirestore.instance.terminate();
await FirebaseFirestore.instance.clearPersistence();

I get no errors thrown and everything seems to be working as it should now.

You should call it immediately after you initialize Firebase, and before you make the first query.

add this to your Login Button 'onPressed':

FirebaseFirestore.instance.terminate();
                FirebaseFirestore.instance
                    .clearPersistence()
                    .then((value) => signinUser(email, password, context));
Related