如何在颤振中添加多通知程序提供程序

时间:2021-04-24 13:10:02

标签: flutter flutter-dependencies flutter-provider

我正在开发食品配送应用程序,并且使用 Provider 作为状态管理架构。问题是当我向我的应用程序添加第二个提供程序时,它会出错。

Widget build(BuildContext context) {
return MaterialApp(
  title: 'Flutter Demo',
  theme: ThemeData(
    primarySwatch: Colors.blue,
  ),
  home: MultiProvider(
    providers: [
      ChangeNotifierProvider<GPSViewModel>(create: (_) => GPSViewModel()),
      ChangeNotifierProvider<OTPViewModel>(create: (_) => OTPViewModel()),
    ],
    child: GPS(),


    ),
    );
   }

错误是

Error: Could not find the correct Provider<OTPViewModel> above this MobileOTP Widget

在 MobileOTP 中,我在初始化状态方法中像这样访问提供程序

   @override
  void initState() {
    super.initState();
    Provider.of<OTPViewModel>(context, listen: false).
    verifyMobileNumber(widget.phone,verificationCompleted,verificationFailed,codeSent,codeAutoRetrievalTimeout);
  }

完整的错误跟踪是这样的

Error: Could not find the correct Provider<OTPViewModel> above this MobileOTP 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 MobileOTP is under your MultiProvider/Provider<OTPViewModel>.
  This usually happens when you are creating a provider and trying to read it immediately.

  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
      builder: (context) {
        // No longer throws
        return Text(context.watch<Example>()),
      }
    ),
  }

What i am doing wrong ?

2 个答案:

答案 0 :(得分:1)

所以基本上问题是“提供者基于 InheritedWidget。只有子小部件可以继承父小部件的状态。”。我试图以其他方式访问它,所以它给了我错误。我将 Material App 与 Multi provider 交换,它解决了问题。

代码现在变成

C:\services\DesktopInfo.exe

就是这样!!!

答案 1 :(得分:0)

不要忽略上下文,在定义它们时使用它,如下所示:

MultiProvider(
    providers: [
      ChangeNotifierProvider<GPSViewModel>(create: (ctx) => GPSViewModel()),
      ChangeNotifierProvider<OTPViewModel>(create: (ctx) => OTPViewModel()),
    ],