Search code examples
flutterflutter-provider

Making an Auth provider in Flutter


I am making a flutter app and I need an Auth provider that will deal with auth things like holding user data, functions for refreshing token etc.

I wish to use this provider inside of my other providers to check if user is logged in before trying to make an api call, and I have stumbled upon ProxyProvider and ChangeNotifierProxyProvider, but I keep getting this error "Error: Could not find the correct Provider above this _InheritedProviderScope Widget".

This is part of my main.dart:

MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (ctx) {
            AuthProvider auth = AuthProvider();
            auth.init();
          },
          lazy: false,
        ),
        ChangeNotifierProxyProvider<AuthProvider, BookingProvider>(
          create: (ctx) => BookingProvider(),
          update: (ctx, authProvider, bookingProvider) => bookingProvider!..updateAuth(authProvider),
        ),
      ],
      child: MaterialApp(...

And here is here I get that error:

Widget build(BuildContext context) {
    BookingProvider bookingProvider = Provider.of<BookingProvider>(context);
    
    return Container();
    }

This screen in under MultiProvider widget in main.dart, and I had no issues with this provider in it before using ChangeNotifierProxyProvider.

Maybe this isn't the best solution since I am still new to flutter, so please if there is a better way let me know.


Solution

  • ChangeNotifierProvider(
              create: (ctx) {
                AuthProvider auth = AuthProvider();
                auth.init();
    
                return auth;
              },
              lazy: false,
            ),

    Solved it, was missing return auth; in create function.