Flutter: внедрение зависимостей с использованием Multiprovider и Consumer в одном дереве - PullRequest
0 голосов
/ 24 февраля 2020

Я пытаюсь внедрить экземпляры служб (которые были созданы на том же уровне дерева) в другого поставщика. Но по дереву при доступе к провайдеру я получаю исключение ProviderNotFoundException. В следующем коде NotificationService зависит от AuthService. Который нужно передать в конструктор. Поэтому я ввожу его, используя Consumer и Provider.value, как указано в документах: https://pub.dev/documentation/provider/latest/provider/Consumer-class.html

Вот псевдокод:

return MultiProvider(
    providers: [
      Provider<AuthService>(
        create: (ctx) => AuthService(_storage),
        dispose: (ctx, v) => v.dispose(),
      ),
      Consumer<AuthService>(
        builder: (context, v, child) {
          return Provider.value(
              value: Provider<NotificationService>(
                create: (ctx) => NotificationService(v),
                dispose: (ctx, v) => v.dispose(),
              ),
              child: child
          );
        },
      )
    ],
    child: MyApp()
);

Где-то вниз по линии дерева, при попытке получить доступ к экземпляру NotificationService, я получаю ProviderNotFoundException:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final NotificationService _ns = Provider.of<NotificationService>(context);
  }
}

Ошибка:

I/flutter ( 4614): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 4614): The following ProviderNotFoundException was thrown building MyApp(dirty, dependencies:
I/flutter ( 4614): [_DefaultInheritedProviderScope<AuthService>]):
I/flutter ( 4614): Error: Could not find the correct Provider<NotificationService> above this MyApp Widget
I/flutter ( 4614): 
I/flutter ( 4614): To fix, please:
I/flutter ( 4614): 
I/flutter ( 4614):   * Ensure the Provider<NotificationService> is an ancestor to this MyApp Widget
I/flutter ( 4614):   * Provide types to Provider<NotificationService>
I/flutter ( 4614):   * Provide types to Consumer<NotificationService>
I/flutter ( 4614):   * Provide types to Provider.of<NotificationService>()
I/flutter ( 4614):   * Ensure the correct `context` is being used.
I/flutter ( 4614): 

Я не полностью понимаю это, и Я почти уверен, что в приведенном выше коде есть ошибка. Что я делаю неправильно?

1 Ответ

2 голосов
/ 24 февраля 2020

То, как вы использовали Provider.value, недопустимо. Но на самом деле вам не нужно Consumer + Provider. Вы можете сделать:

MultiProvider(
  providers: [
    Provider(create: (_) => A()),
    Provider(create: (context) => B(Provider.of<A>(context, listen: false)),
  ],
)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...