flutterdartsupabasesupabase-flutter

Not able to sign out in Flutter Supabase app


I'm new to Flutter and currently building an app using Supabase for authentication.

Everything works fine like user registration, sign-in, etc., but I'm facing an issue with sign-out.

When I press the logout button, the user does get signed out successfully, but the app does not navigate to the login page as expected.

This is Logout Code

    import 'package:expense_tracker/auth/auth_service.dart';
    import 'package:expense_tracker/components/elevated_button.dart';
    import 'package:flutter/material.dart';
    
    class Setting extends StatefulWidget {
      const Setting({super.key});
    
      @override
      State<Setting> createState() => _SettingState();
    }
    
    class _SettingState extends State<Setting> {
      final auth = authService();
    
      void logout() async {
        await auth.signOut();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: CustomButton(
              onPress: logout,
              text: "Logout",
              isSmall: true,
            ),
          ),
        );
      }
    }

This is auth gate code

    import 'package:expense_tracker/pages/home_page.dart';
    import 'package:expense_tracker/pages/login_page.dart';
    import 'package:flutter/material.dart';
    import 'package:supabase_flutter/supabase_flutter.dart';
    
    class AuthGate extends StatelessWidget {
      const AuthGate({super.key});
    
      @override
      Widget build(BuildContext context) {
        return StreamBuilder(
          stream: Supabase.instance.client.auth.onAuthStateChange,
          builder: (context, snapshot) {
            print("Auth state changed: ${snapshot.data}");
    
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const Scaffold(
                body: Center(child: CircularProgressIndicator()),
              );
            }
    
            final session = Supabase.instance.client.auth.currentSession;
            print("Current session: $session");
    
            if (session != null) {
              return HomePage();
            } else {
              return LoginPage();
            }
          },
        );
      }
    }

This is main page code 

    @override
    Widget build(BuildContext context) {
      return MaterialApp(
        debugShowCheckedModeBanner: false,
        themeMode: ThemeMode.system,
        theme: MyThemes.lightTheme,
        darkTheme: MyThemes.darkTheme,
        home: const AuthStateListener(),
        routes: {
          "/login": (context) => const LoginPage(),
          "/register": (context) => const RegisterPage(),
          "/home": (context) => const HomePage(),
          "/expense": (context) => const AddExpense(),
          "/split": (context) => const SplitFriends(),
          "/setting": (context) => const Setting(),
        },
      );
    }

What I’ve Tried:

  1. Wrapping signOut() in a try-catch block — no errors caught.

  2. Verified that auth.signOut() actually signs out the user.

  3. Checked logs, and the AuthGate prints session as null (expected after sign out).

But still not redirected to LoginPage.

What I Expect:

After signing out, the app should automatically redirect to LoginPage (as handled in AuthGate).

NOTE Whenever I am running app without debugging, it's working.


Solution

  • You had to navigate to Setting to logout, so even when the AuthGate rendered page is being updated, you still have the setting page and maybe other pages in your stack.

    A good fix will be to logout then remove all the pages until the first page.

     void logout() async {
       await auth.signOut();
    // Use addPostFrameCallback to ensure navigation happens incase context gets unmounted.
     WidgetsBinding.instance.addPostFrameCallback((_) {
          Navigator.of(context).popUntil((route) => route.isFirst);
        });
    
      }