'Flutter Firebase check if user is signed in anonymously

I am giving Users the option to sign in via Email and Password or anonymously.

Creating and signing in the User with Email and Password works fine, but I am having problems with displaying different contents for anonymously signed in users.

This is how I create them:

final _auth = FirebaseAuth.instance;

    // Create Anonymous User
  Future signInAnonymously() {
    // return _auth.signInAnonymously();
    _auth.signInAnonymously();
  }

If a user chooses to get into the app anonymously in the Auth Form, I trigger following function:

Future submitAnon() async {
await signInAnonymously();
Navigator.push(
  context,
  MaterialPageRoute(
    builder: (context) => HomeScreen(),
  ),
);

}

I am using a Future Builder / Stream to listen to Auth Changes in my main.dart:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final Future<FirebaseApp> _initialization = Firebase.initializeApp();
    return FutureBuilder(
        // Initialize FlutterFire:
        future: _initialization,
        builder: (context, appSnapshot) {
          return MaterialApp(
            debugShowCheckedModeBanner: false,
            title: 'myapp',
            home: appSnapshot.connectionState != ConnectionState.done
                ? SplashScreen()
                : StreamBuilder(
                    stream: FirebaseAuth.instance.authStateChanges(),
                    builder: (ctx, userSnapshot) {
                      if (userSnapshot.connectionState ==
                          ConnectionState.waiting) {
                        return SplashScreen();
                      }
                      if (userSnapshot.hasData) {
                        return HomeScreen();
                      }
                      return AuthScreen();
                    }),
          );
        });
  }
}

What I tried was passing a "isAnon=true" boolean to HomeScreen in submitAnon() but once the user re-opens the app, he is getting into the app from main.dart, where all the users that signed-up via email also get in. Is there a good way to check inside the App if the User is authenticated anonymously to build my widgets depending on that? e.g. showing Authentication Options instead of actual content that is only directed to e-mail&passsword users?



Solution 1:[1]

To check if a user signed in to firebase anonymously. Firebase User class returned has an isAnonymous() method that returns true if the user signs in anonymously. In your code, you can get a firebase user from the streambuilder snapshot. and check if isAnonymous is true. Like below:

StreamBuilder(
                stream: FirebaseAuth.instance.authStateChanges(),
                builder: (ctx, userSnapshot) 
                         { 
                          User user = userSnapshot.data;
                          print('Is user anonymous: ${user.isAnonymous}');
                          },
                            );

should print

'Is user anonymous: true'

if the user signs in anonymously and userSnapshot is not null.

Solution 2:[2]

I think it's too late but here's the simplest way:

FirebaseAuth.instance.currentUser!.isAnonymous // returns a bool

Solution 3:[3]

I would propose you use the SharedPreferences library in order to keep track of of whether the user is anonymous or not. You should simply be able to store the isAnon in Shared Preferences to track whether the user is anonymous or not and from there you could use the Provider library to retrieve the isAnon value throughout the app. With a combinations of these two things you should be able to create the behavior you are looking for.

Please let me know if I misunderstood your question or need a further explanation!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 aolsan
Solution 2 Apealed
Solution 3 MattTheXPat