Error: Could not find the correct Provider<SignInProvider> above this MyApp Widget

Issue

im trying to use StreamProvider with MultiProvider in MaterialApp

when I try accessing the provider, I get the following error:

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

main.dart

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    final provider = Provider.of<SignInProvider>(context, listen: false);
    return MultiProvider(
      providers: [
        StreamProvider<UserModel>.value(value: provider.authStateChange())
      ],
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primaryColor: primaryColor,
          accentColor: secondaryColor,
          textTheme: customTextTheme
        ),
        home: AuthHandler()
      ),
    );
  }
}

class AuthHandler extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    UserModel _userModel = Provider.of<UserModel>(context);
    return (_userModel != null) ? HomeScreen() : LoginScreen();
  }
}

user_model.dart

class UserModel {
  String uid;
  String displayName;
  String photoURL;
  String email;

  UserModel({ this.uid, this.displayName, this.photoURL, this.email, });
}

signin_provider.dart

Stream<UserModel> authStateChange() {
    return firebaseAuth.authStateChanges().map((User user) => (user != null) ? UserModel(uid: user.uid) : null);
  }

Solution

Go to main.dart and Add Your Provider :


Example :

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<ThemeBloc>(
      create: (_) => ThemeBloc(),
      child: Consumer<ThemeBloc>(
        builder: (_, mode, child) {
          return MultiProvider(
            providers: [
              ChangeNotifierProvider<SignInBloc>(
                create: (context) => SignInBloc(),
              ),
              ChangeNotifierProvider<NewsDataBloc>(
                create: (context) => NewsDataBloc(),
              ),
              ChangeNotifierProvider<PopularDataBloc>(
                create: (context) => PopularDataBloc(),
              ),
           
          
            ],
            child: MaterialApp(
           
                home: MyHomePage()),
          );
        },
      ),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
  
      return WelcomePage();
   
  }
}

Answered By – Tasnuva Tavasum oshin

Answer Checked By – Marie Seifert (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.