观察者不更新列表 Flutter

问题描述

我是 Flutter 的新手,我一直在解决这个问题。我使用 mobx 作为状态管理,但尽管我使用的是 Observable 列表,但 Observer 小部件不会更改我在屏幕上的列表, 我的小部件:

return Observer(
  builder: (_) {
    final listProducts = _mainStore.products;
    final listProductsAlter = _mainStore.products;
    return _mainStore.products != null
        ? Expanded(
            child: GridView.count(
              childAspectRatio: (itemWidth / itemHeight),shrinkWrap: true,crossAxisCount: 2,children: List.generate(_mainStore.products.length,(index) {
                // print(" view ${listProducts[index].price}");

                return Container(
                  padding: EdgeInsets.all(10.0),decoration: Boxdecoration(
                      border: Border.all(color: Colors.grey,width: 0.7)),child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,children: [
                      Image(
                        image:
                            NetworkImage(_mainStore.products[index].image),height: 100.0,width: 100.0,),SizedBox(),Text(_mainStore.products[index].title),// Expanded(child: Text(listProducts[index].title)),Text(
                        "R\$ ${listProducts[index].price.toString()}",style: TextStyle(fontWeight: FontWeight.bold),],);
              }),)

        
        : Text('dasdas');
  },);

我的 main.store:

  @observable
  ObservableList<Products> products;

  @observable
  var productsFilterCategory = ObservableList<Products>();

  @observable
  var orderedByPrice = ObservableList<Products>();

  @action
  listAllProducts() async {
    products =
        ObservableList<Products>.of(await _externalRepository.getProducts());
    print(" list all >>> ${products[0].price}");
  }

  @action
  orderByPrice(String c) {
    orderedByPrice = products;
    Comparator<Products> priceComparator = (a,b) => a.price.compareto(b.price);
    products.sort(priceComparator);
  }
}

我正在另一个小部件中调用 orderByPrice() 方法,但我知道列表正在更改,因为我打印了它。

提前致谢。

解决方法

发现我需要使用 Provide 包来使用商店的单个实例。 https://pub.dev/packages/provider