找不到正确的提供者 此主页小部件上方的[

问题描述 投票:0回答:1

我刚刚开始使用提供程序包来重构我的应用程序结构。现在,即使我在下一个BuildContext中的小部件树下调用提供程序,也遇到了以上错误。知道什么可能导致错误吗?据我了解,错误消息中解释的常见错误情况不适用于我。Widget tree

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        Provider(create: (_) => FirebaseAuth.instance.onAuthStateChanged)
      ],
      child: MaterialApp(
          title: "My App",
          home: HomePage()),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return _getLandingPage(Provider.of<FirebaseUser>(context), context);
  }

  Widget _getLandingPage(FirebaseUser firebaseUser, context) {
    if (firebaseUser != null) {
        return CreateProfileFlow();

    } else {
      return PhoneNrInput();
    }
  }
}

错误:

Error: Could not find the correct Provider<FirebaseUser> above this HomePage Widget

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

- 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 HomePage is under your MultiProvider/Provider<FirebaseUser>.
  This usually happen when you are creating a provider and trying to read it immediatly.

  For example, instead of:

  ```
  Widget build(BuildContext context) {
    return Provider<Example>(
      create: (_) => Example(),
      // Will throw a ProviderNotFoundError, because `context` is associated
      // to the widget that is the parent of `Provider<Example>`
      child: Text(context.watch<Example>()),
    ),
  }
  ```

  consider using `builder` like so:

  ```
  Widget build(BuildContext context) {
    return Provider<Example>(
      create: (_) => Example(),
      // we use `builder` to obtain a new `BuildContext` that has access to the provider
      builer: (context) {
        // No longer throws
        return Text(context.watch<Example>()),
      }
    ),
  }
  ```

If none of these solutions work, consider asking for help on StackOverflow:
https://stackoverflow.com/questions/tagged/flutter
flutter dart provider state-management
1个回答
0
投票

[FirebaseAuth.instance.onAuthStateChangedStream,但是您使用Provider而不是StreamProvider来显示值。

同样,如果要读取值,则有两个选择:

  • 使用StreamProvider代替Provider

    StreamProvider(
      create: (_) => FirebaseAuth.instance.onAuthStateChanged,
    ),
    
  • 保持使用Provider,并使用context.watch<Stream<FirebaseUser>>获得流:

    StreamBuilder(
      stream: context.watch<Stream<FirebaseUser>>(),
      builder: (context, snapshot) {
        ...
      },
    );
    
© www.soinside.com 2019 - 2024. All rights reserved.