Flutter Getx 与 grouped_list :在构建期间调用 setState() 或 markNeedsBuild()

时间:2021-04-01 17:20:39

标签: getx

当我想使用 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

1 个答案:

答案 0 :(得分:0)

好的!在使用 Rx 或 GetX 时,您必须了解一些基本的东西。 Obx 小部件实际上是用于 可观察 值的 观察者 小部件。或者您可以为 StreamStreamBuilder。 因此,每当您尝试在没有任何可观察变量的情况下使用它时,它 (Obx) 都会抛出异常。 您的代码在您的 Obx 小部件中不包含任何可观察的值。这就是这里的问题。 因此,与其在 build 方法中使用 var _elements = homeController.cartItems,不如直接在 Obx 小部件内的 GroupedListView 中使用 elements: homeComtroller.cartItems

另外不要忘记通过添加 .obsfinal cartList=[].obs

来使您的 cartList 可见