如何使用 Riverpod 从流中填充列表而不使用构建小部件

问题描述

我正在尝试创建一个应用程序

  1. 我有一份产品清单
  2. 我使用 StreamProvider 从 Firebase 获取此列表,并且运行良好。
  3. 我希望首先将所有产品放入购物车。原因是因为在这个购物应用中,用户应该首先看到购物车中的所有产品,然后再决定他们想要保留或移除哪些产品。

这是我的 StreamProvider。此代码工作正常。

final productListStreamProvider = StreamProvider.autodispose<List<ProductModel>>((ref) {
  CollectionReference ref = FirebaseFirestore.instance.collection('products');
  return ref.snapshots().map((snapshot) {
    final list = snapshot.docs
        .map((document) => ProductModel.fromSnapshot(document))
        .toList();
    return list;
  });
});

所以,问题来了。拿到产品列表后,我尝试做以下事情。

class ListProducts extends ConsumerWidget {
  ListProducts({Key key}) : super(key: key);
  final double itemHeight = 130;
  final double itemWidth = Get.width / 2 - 100;

  @override
  Widget build(BuildContext context,ScopedReader watch) {
   final productStream = watch(productListStreamProvider);
   final cartList = watch(cartRiverpodProvider.state);
   int i;
   for(i=0;i<productStream.data.value.length;i++)
     {
       context.read(cartRiverpodProvider).add(
           productStream.data.value[i]);
     }

   return ListView.builder(
       padding: const EdgeInsets.all(8),itemCount: productStream.data.value.length,itemBuilder: (BuildContext context,int index) {
         return ListTile(
             title: Text(productStream.data.value[index].productName),subtitle: Text('Date: ${timeago.format(productStream.data.value[index].createdOn.toDate())} Tracking Number: ${productStream.data.value[index].receivedTrackingNumber} Weight: ${productStream.data.value[index].weight.toString()} grams'),onTap: () {
              Navigator.pushNamed(context,'/products',arguments: productStream.data.value[index].id.toString());
         },);
       }
   );
  }

  }

我收到此错误

======== Exception caught by widgets library =======================================================
The following Error was thrown building ListProducts(dirty,dependencies: [UncontrolledProviderScope],state: _ConsumerState#09d50):
Instance of 'Error'

所以,我的问题是。

  1. 我是否采取了错误方法?如果是这样,拥有属于的列表的最佳方法是什么 到由来自 (productListStreamProvider) 的流填充的另一个提供程序 (cartRiverpodProvider)?

  2. 对于这种情况,我什至需要使用两个提供程序吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)