如何在 Flutter 中使用多个 ChangeNotifierProvider?

How to use more than one ChangeNotifierProvider in Flutter?

我最近开始使用 provider 进行状态管理,我知道如何一次使用一个。

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ChangeNotifierProvider<Reader>(
        create: (context) => new Reader(),
        child: _HomeBody(),
      ),
    );
  }
}

但现在我有两个不同的 类,我想添加它们并能够在我的小部件树中访问。

如何在 Flutter 中添加多个 ChangeNotifierProvider

您可以使用 MultiProvider

这篇指南对我有帮助,希望对你也有帮助...

MultiProvider(
  providers: [
    ChangeNotifierProvider<Counter>(builder: (context) => Counter(0)),
    ProxyProvider<Counter, ThemeSwitch>.custom(
      builder: (context, counter, previous) {
        final theme = previous ?? ThemeSwitch(ThemeState.light);
        theme.themeState =
              (counter.value > 5) ? ThemeState.dark : ThemeState.light;
        return theme;
      },
      dispose: (context, value) => value.dispose(),
      providerBuilder: (_, value, child) =>
          ChangeNotifierProvider.value(notifier: value, child: child),
    ),
  ],
)

一个选项(不推荐)是嵌套 2 个提供商:

ChangeNotifierProvider<Reader>(
  create: (_) => Reader(),
  child: ChangeNotifierProvider<SomethingElse>(
    create: (_) => SomethingElse(),
    child: ChangeNotifierProvider<AnotherThing>(
      create: (_) => AnotherThing(),
      child: someWidget,
    ),
  ),
),

不推荐这样做,因为如文档所述:

When injecting many values in big applications, Provider can rapidly become pretty nested:

但是,来自 Provider package itself is to use the MultiProvider 的另一个建议:

MultiProvider(
  providers: [
    ChangeNotifierProvider<Reader>(create: (_) => Reader()),
    ChangeNotifierProvider<SomethingElse>(create: (_) => SomethingElse()),
    ChangeNotifierProvider<AnotherThing>(create: (_) => AnotherThing()),
  ],
  child: _HomeBody(),
)

两种方法的工作原理相同,但第二种方法更具可读性。正如文档中所说:

The behavior of both examples is strictly the same. MultiProvider only changes the appearance of the code.

示例改编自 provider flutter package page 并适合您的情况。