Search code examples
fluttergetflutter-getxflutter-listview

How to update only one widget in a ListView in Flutter when its data changes?


class ListNumbersPage extends GetView<MyController> {
  final colors = [
    Colors.red,
    Colors.green,
    Colors.pinkAccent,
    Colors.blue,
    Colors.grey,
    Colors.cyan,
  ];
  final random = Random();

  @override
  Widget build(BuildContext context) {
    Get.put(MyController());

    return Scaffold(
      appBar: AppBar(title: const Text('ListNumbersPage')),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              itemCount: controller.listOfFiles.length,
              itemBuilder: (_, index) {
                final currentFile = controller.listOfFiles[index];
                return Container(
                  padding: const EdgeInsets.symmetric(vertical: 32),
                  color: colors[random.nextInt(colors.length)],
                  child: Row(
                    children: [
                      Obx(
                        () {
                          MyLogs.warning('UPDATED INDEX : $index');
                          return MyIconButton(
                            onTap: () {
                              doLike(controller.listOfSelection ?? [], currentFile.value.fileId, index);
                            },
                            iconData: FontAwesomeIcons.solidHeart,
                            color: isExist(controller.listOfSelection ?? [], currentFile.value.fileId, index)
                                ? isLiked(controller.listOfSelection ?? [], currentFile.value.fileId)
                                    ? AppColor.redDark
                                    : AppColor.white
                                : AppColor.white,
                          );
                        },
                      ),
                      Text(controller.listOfFiles[index].value.fileId),
                    ],
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

bool isExist(List<Rx<LikeModel>> listOfSelection, String fileId, int index) {
  try {
    if (listOfSelection.length >= index) {
      final item = listOfSelection.firstWhereOrNull((e) => e.value.fileId == fileId);
      return item != null;
    } else {
      return false;
    }
  } catch (e) {
    MyLogs.debug(e.toString());
    return false;
  }
}

bool isLiked(List<Rx<LikeModel>> listOfSelection, String fileId) {
  try {
    return listOfSelection.firstWhere((e) => e.value.fileId == fileId).value.isLiked;
  } catch (e) {
    MyLogs.debug(e.toString());
    return false;
  }
}

void doLike(List<Rx<LikeModel>> listOfSelection, String fileId, int index) {
  try {
    final item = listOfSelection.firstWhere((element) => element.value.fileId == fileId);
    final index = listOfSelection.indexOf(item);
    final isLiked = item.value.isLiked;

    listOfSelection[index].value = item.value.copyWith(
      isLiked: !isLiked,
    );
  } catch (e) {
    MyLogs.debug(e.toString());
  }
}

class MyController extends GetxController {
  final listOfFiles = [
    "IMAGE001",
    "IMAGE002",
    "IMAGE003",
    "IMAGE004",
    "IMAGE005",
    "IMAGE006",
    "IMAGE007",
    "IMAGE008",
    "IMAGE009",
    "IMAGE010",
  ].map((e) => LikeModel(e, false).obs).toList();

  List<Rx<LikeModel>>? listOfSelection;

  @override
  void onInit() {
    listOfSelection = listOfFiles;
    super.onInit();
  }
}

class LikeModel {
  String fileId;
  bool isLiked;

  LikeModel(this.fileId, this.isLiked);

  LikeModel copyWith({
    String? fileId,
    bool? isLik
  }) {
    return LikeModel(
      fileId ?? this.fileId,
      isLiked ?? this.isLiked,
    );
  }
}

I'm facing an issue in my Flutter app where I have a ListView displaying a list of items, each item containing a like button. The problem arises when I press the like button for a specific item – instead of updating only that particular like button, the entire ListView gets rebuilt, causing performance overhead.

What I want to achieve is to update only the specific like button widget whose data (like status) has changed, without affecting the rest of the list items.

I've tried using various state management techniques such as Obx, GetBuilder, and even experimented with Provider, but none seem to provide a solution that updates only the targeted widget.

Could someone please guide me on how to efficiently update just the relevant widget in the ListView when its associated data changes? Any insights, code snippets, or examples would be highly appreciated.

Thank you!


Solution

  • I have solved the issue by creating a separate StatefulWidget and removing obx for the like button. It manages state locally using setState to ensure only the clicked widget updates.

    class LikeButtonWidget extends StatefulWidget {
      final Rx<LikeModel> currentFile;
    
      LikeButtonWidget({required this.currentFile});
    
      @override
      _LikeButtonWidgetState createState() => _LikeButtonWidgetState();
    }
    
    class _LikeButtonWidgetState extends State<LikeButtonWidget> {
      @override
      Widget build(BuildContext context) {
        return IconButton(
          onPressed: () {
            setState(() {
              widget.currentFile.value = widget.currentFile.value.copyWith(isLiked: !widget.currentFile.value.isLiked);
            });
          },
          icon: Icon(FontAwesomeIcons.solidHeart, color: widget.currentFile.value.isLiked ? AppColor.redDark : AppColor.white),
        );
      }
    }