【问题标题】:How to create multiple instance of same provider in flutter如何在颤振中创建同一提供者的多个实例
【发布时间】:2021-07-10 05:52:59
【问题描述】:

我正在使用提供程序来获取数据并通知侦听器,如下所示:

class CategoryProvider with ChangeNotifier {

  Future<void> getData() async {
     ......
     ......
     notifyListeners();
   }

}

我的CategoryListView 小部件正在监听此提供程序,如下所示:

Widget build(BuildContext context) {
    var collectionData = Provider.of<CategoryProvider>(context);
}

我正在推送CategoryListView 的新实例,如下所示:

Navigator.of(context).pushNamed(CategoryListView.routeName);

我正在从CategoryListView 小部件本身推送CategoryListView 的新实例。 它在推送新实例时工作正常,但在导航返回时,所有CategoryListView 小部件都显示最新的CategoryListView 小部件的数据,因为它正在侦听同一提供程序。 如何创建提供者的新实例并将其关联到小部件实例?有没有更好的方法来处理这个问题?

【问题讨论】:

  • 曾经解决过这个问题吗?
  • @Lee ,我找到了解决方案并作为答案发布。请检查它是否对您有帮助。

标签: flutter dart flutter-provider


【解决方案1】:

我已经解决了它,我正在发布解决方案,以便它可以帮助某人。

provider 的新实例在CategoryListView 类中声明如下:

  final CategoryProvider collectionData = CategoryProvider();

同样,我没有将 CategoryListView 的关联数据作为导航器参数传递,而是将其作为构造函数值传递,以便可以在 initState() 函数中访问这些值。

因此,CategoryListView 的新实例的推送更改为

Navigator.of(context).pushNamed(CategoryListView.routeName);

Navigator.push(context, MaterialPageRoute(builder: (context) => 
CategoryPage(constructorValue) ));

initState() 函数上,为提供者设置必要的值并进行必要的函数调用。

 collectionData.catalogueId = widget.catalogueId;
 collectionData.loadNextPage();

Widget build(BuildContext context)上,监听提供者从

     Widget build(BuildContext context) {
    var collectionData = Provider.of<CategoryProvider>(context);
}

Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Color(0xff04063E),
        title: Text(widget.catalogueName != null ? widget.catalogueName : ""),
        
      ),
      body: ChangeNotifierProvider.value(
        value: collectionData,
        child: Consumer<CategoryProvider>(builder: (_, ctl, __) {
          return _buildUI(collectionData);
        }),
      ),
    );
  }

其中_buildUI(collectionData) 是一个从提供实例collectionData 构建UI 的函数。

另外,在 dispose 上释放提供者实例:

@override
  void dispose() {
    collectionData.dispose();
    super.dispose();
  }

【讨论】:

    猜你喜欢
    • 2021-08-16
    • 2021-11-01
    • 2022-01-15
    • 2021-05-16
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 2020-05-10
    相关资源
    最近更新 更多