【问题标题】:Flutter Getx vs grouped_list : setState() or markNeedsBuild() called during buildFlutter Getx vs grouped_list:在构建期间调用 setState() 或 markNeedsBuild()
【发布时间】:2021-06-28 17:10:16
【问题描述】:

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

【问题讨论】:

    标签: flutter-getx


    【解决方案1】:

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

    别忘了通过添加.obs 像final cartList=[].obs

    让您的cartList 可观察

    【讨论】:

    • 我的荣幸。将此视为已接受的答案并进行投票,以便对其他人有所帮助。
    猜你喜欢
    • 2020-12-12
    • 2020-12-28
    • 2021-01-06
    • 2021-05-31
    • 2021-08-24
    • 2020-08-11
    • 2020-04-10
    相关资源
    最近更新 更多