如何在Flutter中使用多个ChangeNotifierProvider? [英] How to use more than one ChangeNotifierProvider in Flutter?

查看:164
本文介绍了如何在Flutter中使用多个ChangeNotifierProvider?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I recently started using provider for my state management and I know how to use one at a time.

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

但是现在我有两个不同的类,我想添加两个类并能够在我的小部件树中进行访问.

But now I have two different classes and I want to add both of them and be able to access in my widget tree.

如何在 Flutter 中添加多个 ChangeNotifierProvider ?

推荐答案

一个选项(不建议)是嵌套2个提供程序:

One option (not recommended) is to nest 2 Providers:

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

不建议这样做,因为如文档所述:

This is not recommended because, as the documentation states:

在大型应用程序中注入许多值时,Provider可能会迅速嵌套:

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

但是,提供程序包本身的另一个建议是使用

But, another suggestion from the Provider package itself is to use the MultiProvider:

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

两种方法的工作原理相同,但第二种方法更具可读性.作为文档文字:

Both approaches work the same but the second one is more readable. As the documentation words:

两个示例的行为严格相同.MultiProvider仅更改代码的外观.

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

根据提供者轻巧包装页面改编而成的示例,并根据您的情况进行修改.

Example adapted from the provider flutter package page and adapted to your case.

这篇关于如何在Flutter中使用多个ChangeNotifierProvider?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆