I have a flutter based web app which uses Firebase for phone authentication. I am able to authenticate using the firebase. The problem arises when I refresh or reload the app. It starts from the scratch asking me to enter my mobile no and then the OTP...
After searching on the web I found some people suggesting to place the following code (_auth.setPersistence(Persistence.LOCAL);). Unfortunately that does not work!!
@override
void initState() {
super.initState();
_auth = FirebaseAuth.instance;
_auth.setPersistence(Persistence.LOCAL);
isLoading = false;
}
@override
Widget build(BuildContext context) {
user = _auth.currentUser;
return isLoading
? const Scaffold(
body: Center(
child: CircularProgressIndicator(),
),
)
: user == null
? const Login()
: const Home();
}
Is there a way to avoid asking the user the phone number and OTP every time they visit the app?
Firebase store the credentials locally on most browser environments automatically. But restoring them requires a call to the server, which is an asynchronous operation that may not have completed by the time your build
method is first called.
To properly pick up the user state and respond to it, use an auth state listener, as shown in the first code sample in the documentation on getting the current user. The FirebaseAuth.instance.authStateChanges()
in that code sample is a stream, so you'll want to use a StreamBuilder
in your UI to deal with the auth state.