0

当我想使用 Getx 控制器获取数据并使用 grouped_list 将其显示为组列表时,因为我想让我的购物车被分组。但我得到以下错误,有人可以帮忙吗?谢谢。

下面的代码:

class CartList extends StatelessWidget {
  final HomeController homeController = Get.find();

  @override
  Widget build(BuildContext context) {
    var _elements = homeController.cartItems;
    return Obx(() => GroupedListView<dynamic, String>(
          elements: _elements,
          groupBy: (element) => element['group'],
          groupSeparatorBuilder: (String groupByValue) => Text(groupByValue),
          itemBuilder: (context, dynamic element) => Text(element['name']),
          itemComparator: (item1, item2) =>
              item1['name'].compareTo(item2['name']), // optional
          useStickyGroupSeparators: true, // optional
          floatingHeader: true, // optional
          order: GroupedListOrder.ASC, // optional
        ));
......

这里的错误:

The following assertion was thrown building GroupedListView<dynamic, String>(dirty, state: _GroupedListViewState<dynamic, String>#adcb0):
setState() or markNeedsBuild() called during build.

This Obx widget cannot be marked as needing to build because the framework is already in the process of building widgets.  A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase.
The widget on which setState() or markNeedsBuild() was called was: Obx
  dirty
  state: _ObxState#c2d8d
The widget which was currently being built when the offending call was made was: GroupedListView<dynamic, String>
  dirty
  state: _GroupedListViewState<dynamic, String>#adcb0
4

1 回答 1

1

好的!当你使用 Rx 或 GetX 时,你必须了解一些基本的东西。Obx部件实际上是可观察值的观察者小部件。或者你可以说StreamBuilder for Stream。因此,只要您尝试在没有任何可观察变量的情况下使用它(Obx),它就会抛出异常。您的代码不包含 Obx 小部件内的任何可观察值。这就是这里的问题。因此,您应该直接在 Obx 小部件内的 GroupedListView中使用,而不是在您的构建方法中使用。var _elements = homeController.cartItemselements: homeComtroller.cartItems

也不要忘记通过添加like使您的cartList可观察.obsfinal cartList=[].obs

于 2021-04-02T18:50:38.580 回答