skip to Main Content

I’m trying to do that using firebase ui auth. But initially trying to get it working just using signInWithEmailPassword().

It seems like I can use SharedPreferences to save email and password after FirebaseAuth.instance.signInWithEmailAndPassword(), but how would I feed that back since the app listens to FirebaseAuth.instance.authStateChanges()?

2

Answers


  1. Firebase Authentication, by design, requires an internet connection to authenticate users since it relies on the Firebase server to validate the user’s credentials. So, it is not possible to re-login without an internet connection using FirebaseAuth.

    However, you can implement offline authentication using a custom solution. One common approach is to use a secure local storage to store a token or a flag indicating the user’s authentication state.

    Create a custom authentication state stream that combines the Firebase auth state with your local storage’s auth state. This way, your app can still listen to auth state changes and work seamlessly with both online and offline authentication.

    Example:

    class CustomAuth {
      final FirebaseAuth _firebaseAuth;
      StreamController<User?> _authStateController = StreamController<User?>.broadcast();
    
      CustomAuth._privateConstructor(this._firebaseAuth) {
        // Combine Firebase Auth state with local storage auth state
        _firebaseAuth.authStateChanges().listen((firebaseUser) async {
          if (firebaseUser == null) {
            // If Firebase user is null, check local storage for the user
            SharedPreferences prefs = await SharedPreferences.getInstance();
            String? localUserId = prefs.getString('localUserId');
            if (localUserId != null) {
              // If a local user exists, create a custom user object
              // Note: You can replace 'User' with your own custom user model if needed
              User customUser = User(localUserId); // Replace with your custom user model
              _authStateController.add(customUser);
            } else {
              _authStateController.add(null);
            }
          } else {
            _authStateController.add(User(firebaseUser.uid));
          }
        });
      }
    
      static final CustomAuth _instance = CustomAuth._privateConstructor(FirebaseAuth.instance);
    
      static CustomAuth get instance => _instance;
    
      Stream<User?> get authState => _authStateController.stream;
    
      void dispose() {
        _authStateController.close();
      }
    }
    
    class User {
      final String id;
      User(this.id);
    }
    
    
    Login or Signup to reply.
  2. To stay logged in till you logout by your self, you have to check that is the user logged in before or not on your Splash Screen or LoginPage.

    First, enable Firebase Authentication Persistence inside your main() void:

    await FirebaseAuth.instance.setPersistence(Persistence.LOCAL);
    

    After that make a bool variable to check the User State:

      bool _isAuthenticated = false;
    

    Then, Add this to your initState() void to check if the User is authenticated on app launch or page initial:

     FirebaseAuth.instance.authStateChanges().listen((user) {
      if (user != null) {
        setState(() {
          _isAuthenticated = true;
        });
      }
    });
    

    and Finally, use the bool as a condition before your Pages Widget:

      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'My Firebase App',
          home: _isAuthenticated ? HomePage() : LoginPage(),
        );
      }
    

    That’s way to check a user to see if he/she logged in or not, I use this way for a long time hope it helps you well…

    and for using your app without internet you and use this:

    db.settings = const Settings(
      persistenceEnabled: true,
      cacheSizeBytes: Settings.CACHE_SIZE_UNLIMITED,
    );
    

    and check this link to see more about it, it’s very useful for me 😉
    The Link of Access data offline

    StaySafe

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search