代码之家  ›  专栏  ›  技术社区  ›  magnump0

如何在Flutter中将模型与提供者分离?

  •  0
  • magnump0  · 技术社区  · 4 年前

    假设我们的models/文件夹中有一个模型:

    class ProductModel {
      final String id;
      ProductModel(this.id);
    }
    

    然后我们相应地在providers/文件夹中为此模型创建一个提供者:

    class ProductProvider with ChangeNotifier {...}
    

    问题是如何在这个提供者中扩展模型,以避免重复?解决方案:

    class ProductProvider extends ProductModel with ChangeNotifier {...}
    

    如果我们以后创建另一个提供程序,则不起作用 ProductsProvider (复数)代表列表。

    0 回复  |  直到 4 年前
        1
  •  1
  •   Michel Feinstein    4 年前

    提供者ChangeNotifier架构与您展示的略有不同,但您基本上都在那里。

    您应该:

    class ProductViewModel with ChangeNotifier {
      final String id;
      ProductModel(this.id);
    }
    

    就是这样,现在你可以通过这个了 ProductViewModel 使用a ChangeNotifierProvider 如您所见 here .

    推荐文章