0

When I would like to use Getx controller to fetch data and use grouped_list to display it to be a group list, cause I want to make my shopping cart to be grouped. but I got below error, anyone can help on it? thanks.

Code below:

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
        ));
......

Error here:

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
Waytoon
  • 1
  • 1
  • 1

1 Answers1

2

Okay! You have to understand some basic things when you are using Rx or GetX. An Obx widget is actually a observer widget for observable value. Or you could say StreamBuilder for Stream. So it (Obx) will throw exception whenever you try to use it without any observable variable. Your code doesn't include any observable value inside of your Obx widget. That's the issue here. So instead of using var _elements = homeController.cartItems in your build method, you should directly use elements: homeComtroller.cartItems in your GroupedListView inside the Obx widget.

Also don't forget to make your cartList observable by adding .obs like final cartList=[].obs

S. M. JAHANGIR
  • 4,324
  • 1
  • 10
  • 30