Supabase auth currentuser id null sometimes

43 views Asked by At

I'm experiencing intermittent occurrences of the 'auth uid null' error. Upon initial login to the app, everything functions correctly. However, if I revisit the app after a couple of hours, I encounter the Null check operator used on a null value error. Sometimes, this error persists briefly before the screen loads properly, but often it remains stuck with the error message.

It seems like there may be an issue with the authentication refresh token?

Service

class SupabaseService {
  Future<User> getProfile() async {
    try {
      final uid2 = supabase.auth.currentUser!.id;
    } catch (e) {
      print('failed getting uid value');
    }
    final uid = supabase.auth.currentUser!.id;
    final data = await supabase.rpc('get_my_profile', params: {'user_uid': uid}).single();
    final profile = User.fromJsonSimple(data);
    return profile;
  }
  }

Then using the method inside riverpod notifier

class ProfileNotifier extends _$ProfileNotifier {
  @override
  Future<User> build() async {
    return await ref.watch(supabaseProvider).getProfile();
  }
}

main screen

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return ResponsiveSizer(builder: (context, orientation, screentype) {
      return MaterialApp(
        debugShowCheckedModeBanner: false,
        title: "Supa App',
        theme: ThemeData(textTheme: AppTheme.lightTexTheme),
        home: const Scaffold(body: SplashScreen()),
      );
    });
  }
}

Flash screen

class SplashScreen extends StatefulWidget {
  const SplashScreen({super.key});

  @override
  SplashScreenState createState() => SplashScreenState();
}

class SplashScreenState extends State<SplashScreen> {
   bool _redirectCalled = false;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _redirect();
  }

  Future<void> _redirect() async {
    await Future.delayed(Duration.zero);
    if (_redirectCalled || !mounted) {
      return;
    }

    _redirectCalled = true;

    final session = supabase.auth.currentSession;
    if (session == null) {
      context.goNamed('login');
    } else {
      context.goNamed('account');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: CircularProgressIndicator(
        color: AppTheme.darkBlue,
      )),
    );
  }
}
0

There are 0 answers