flutter: getx RxList not run obx builder

Issue

I am using getx on my project . I have RxList and buy Obx I shows my data on widget:

  RxList<VocabularyModel> vocabs = RxList();

and widget:

   return Scaffold(
      body: SafeArea(
        child: Obx(
          () => ListView.builder(
            // ignore: invalid_use_of_protected_member
            itemCount: controller.vocabs.value.length,
            itemBuilder: (context, index) {
              return Padding(
                padding: EdgeInsets.symmetric(vertical: 8.h, horizontal: 8),

In controller I have method to remove on object in vocabs:

  void changeToRememberState(int index) {
    final upateItem = vocabs.value[index].copyWith(remember: true);
    vocabs.value.removeAt(index);
    // repository.changeToRememberState(index, upateItem);
  }

But when I remove object from vocabs, Obx builder not triggered? Why? I remove one element from RxList, Why RxList not fire?

Solution

Lists are reactive (Rx) by default. Therefore if you are using RxList or [].obs you should not use .value to access it. Or I should say, you should not ignore: invalid_use_of_protected_member. That’s why your Obx isn’t triggering rebuild when you are removing. Because you are removing the underlying List elements and not from the stream.

Unless you use Rx<List<VocabularyModel>>, you should not use vocabs.value.
Therefore removing .value from vocabs will fix the rebuild issue.

  • Widget:

    return Scaffold(
    body: SafeArea(
      child: Obx(
        () => ListView.builder(
          itemCount: controller.vocabs.length,
          itemBuilder: (context, index) {
            return Padding(
              padding: EdgeInsets.symmetric(vertical: 8.h, horizontal: 8),
    
  • Controller:

    void changeToRememberState(int index) {
       final upateItem = vocabs[index].copyWith(remember: true);
       vocabs.removeAt(index);
      }
    

Answered By – S. M. JAHANGIR

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.