简体   繁体   中英

Flutter MultiProvider Not found

Error: Could not find the correct Provider above this AuthenticationWrapper Widget

This happens because you used a BuildContext that does not include the provider of your choice. There are a few common scenarios:

  • You added a new provider in your main.dart and performed a hot-reload. To fix, perform a hot-restart.

  • The provider you are trying to read is in a different route.

    Providers are "scoped". So if you insert of provider inside a route, then other routes will not be able to access that provider.

  • You used a BuildContext that is an ancestor of the provider you are trying to read.

    Make sure that AuthenticationWrapper is under your MultiProvider/Provider. This usually happens when you are creating a provider and trying to read it immediately

    import 'package:firebase_auth/firebase_auth.dart';
    import 'package:firebase_core/firebase_core.dart';
    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    import 'package:google_fonts/google_fonts.dart';
    import 'package:park_app/app_styles.dart';
    import 'package:provider/provider.dart';
    import 'package:shared_preferences/shared_preferences.dart';
    import './views/pages.dart';
    import 'views/authentication/authentication_service.dart';
    import 'Home_Page.dart';
    
    bool? seenOnboard;
    
    Future<void> main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await Firebase.initializeApp();

      // to show status bar
      SystemChrome.setEnabledSystemUIOverlays(
          [SystemUiOverlay.bottom, SystemUiOverlay.top]);
      // to load onboard for the first time only
      SharedPreferences pref = await SharedPreferences.getInstance();
      seenOnboard = pref.getBool('seenOnboard') ?? false; //if null set to false
    
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MultiProvider(
          providers: [
            Provider<AuthenticationService>(
              create: (_) => AuthenticationService(FirebaseAuth.instance),
            ),
            StreamProvider(
                initialData: null,
                create: (context) =>
                    context.read<AuthenticationService>().authStateChanges),
          ],
          child: MaterialApp(
            debugShowCheckedModeBanner: false,
            title: 'Park App',
            theme: ThemeData(
              textTheme: GoogleFonts.manropeTextTheme(
                Theme.of(context).textTheme,
              ),
              primarySwatch: Colors.blue,
              scaffoldBackgroundColor: kScaffoldBackground,
            ),
            home: seenOnboard == true ? AuthenticationWrapper() : OnBoardingPage(),
          ),
        );
      }
    }
    
    class AuthenticationWrapper extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        final firebaseUser = context.watch<User>();
    
        if (firebaseUser != null) {
          return HomePage();
        }
        return LoginPage();
      } 
    }

Make sure to specify the generic type on StreamProvider :

StreamProvider<User?>(
  ...
)

Note that you have set null as initialData, so your widget likely needs to handle null users. Meaning you need to do:

final user = context.watch<User?>()

install provider by running the command below:

flutter pub add provider and then in your main.dart file, import it import 'package:provider/provider.dart';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM