0

Hi I'm new to Flutter and Provider and can't make sense of this error. Basically I'm using MultiProvider to manage the states like below, and this works really great for one of them (Auth) but not other(User) even though I'm using them in the same way. I get this error.

Note there are actually more providers, but simplified it for sake of simpler code example

Error

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following ProviderNotFoundException was thrown building StartPage(dirty, dependencies: [_InheritedProviderScope<Auth>, _InheritedProviderScope<UserLocation>, _InheritedProviderScope<UserState>, _InheritedProviderScope<BottomNavigationBarProvider>]):
Error: Could not find the correct Provider<User> above this StartPage Widget

To fix, please:

  * Ensure the Provider<User> is an ancestor to this StartPage Widget
  * Provide types to Provider<User>
  * Provide types to Consumer<User>
  * Provide types to Provider.of<User>()
  * Ensure the correct `context` is being used.

If none of these solutions work, please file a bug at:

Main.dart

class SchoolApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Demo',
        home: MultiProvider(
          providers: [
            ChangeNotifierProvider(create: (_) => Auth()),
            ChangeNotifierProvider(create: (_) => User()),
          ],
          child: HomePage(),
        ));
  }
}

class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => new _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    UserState _userState = Provider.of<UserState>(context);
    switch (_userState.status) {
      case UserStatus.UnAuthenticated:
        return LoginScreen();
      case UserStatus.Authenticated:
        return StartPage();
    }
  }
}

StartPage.dart

class StartPage extends StatelessWidget with ChangeNotifier {

  Timer timer;

  @override
  Widget build(BuildContext context) {
    final _auth = Provider.of<Auth>(context);
    final _user = Provider.of<User>(context, listen: true);
...

User.dart

class User extends ChangeNotifier{
  Firestore db = Firestore.instance;

  String _userId, _firstName, _lastName, _school, _email, _description, _employer, _title, _name;
  List<String> _ideologies, _interests, _religions;
  UserType _userType;
...

Auth.dart

class Auth extends ChangeNotifier {
  final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;

  Future<String> signInWithEmailAndPassword(String email, String password) async {
    final AuthResult authResult = await _firebaseAuth.signInWithEmailAndPassword(email: email, password: password);
    notifyListeners();
    return authResult.user.uid.toString();
  }
...

3 Answers3

1
class SchoolApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
        providers: [
         ChangeNotifierProvider<Auth>(create: (_) => Auth()),
         ChangeNotifierProvider<User>(create: (_) => User()),
        ],
        child: MaterialApp(
        title: 'Flutter Demo',
        home: HomePage(),
        ));
  } 
}

Wrap your MaterialApp with MultiProvider. I might have made some bracket issue in my code above

Sirus
  • 141
  • 1
  • 10
  • This doesn't work either, I'm getting the same error, but in any case I shouldn't have to put it above my MaterialApp either since ideally you'd want to put it as far down the three as possible, right? – floyergilmour May 23 '20 at 16:01
  • Ohh my bad I didn't saw that you aren't defining type ChangeNotifierProvider, you can see changes in my original answer. Tell me if it still shows an error. – Sirus May 23 '20 at 23:39
0

Try to wrap with Consumer the widget that requires to get date from provider:

  Foo(
  child: Consumer<Auth, User>(
    builder: (context, auth, user, child) {
      return YourWidget(a: yourProviderData, child: child);
    },
    child: Baz(),
  ),
)

You can try also wrap your code with the widget Builder(builder: (context) => ), to have access to the nearest context reference.

Gauris Javier
  • 387
  • 4
  • 11
  • This didn't really work for me, same error. If I understand correctly from this post https://stackoverflow.com/questions/58774301/when-to-use-provider-ofx-vs-consumerx-in-flutter consumer uses provider.of under the hood – floyergilmour May 26 '20 at 20:22
0

Answering my question for visibility. So found the answer to my question here. https://github.com/rrousselGit/provider/issues/422#issuecomment-632030627

Basically I imported the package in the wrong way, I did import 'path/file.dart'

Instead of specifying the full path import 'package:/path/file.dart'