When I add an item to the obs sublist, the widget is not updating. If I add an item to the main list, it's working fine.
Please help me to properly implement reactive.
home_controller.dart
import 'package:get/get.dart';
class FoodCategory {
final String name;
final List<String> foods;
FoodCategory({required this.name, required this.foods});
}
class HomeController extends GetxController {
late final List<FoodCategory> foodList;
@override
void onInit() {
super.onInit();
foodList = [
FoodCategory(name: "Fruits", foods: ["Apple", "Orange"]),
FoodCategory(name: "Vegetable", foods: ["Carrot", "Beans"])
].obs;
}
void addFood(index, food) {
foodList[index].foods.add(food); // Not Working. Item added but UI not re-rendered.
print(food + " added");
}
void addCategory(FoodCategory foodcategory) {
foodList.add(foodcategory); // Working Fine.
print("New food category added");
}
}
home_view.dart
class HomeView extends GetView<HomeController> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Example"),
),
body: Container(
child: Obx(
() => Column(
children: [
for (var foodCat in controller.foodList)
Container(
width: 300,
height: 100,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(foodCat.name),
Column(
children: [for (var food in foodCat.foods) Text(food)],
),
TextButton(
onPressed: () => controller.addFood(0, "Banana"), // Not Working
child: Text("Add Food"))
],
),
)
],
),
),
),
floatingActionButton: FloatingActionButton(
child: Text("Add Category"),
onPressed: () => controller
.addCategory(FoodCategory(name: "pulse", foods: ["wheat"]))), // Working.
);
}
}
I finally figured out.
Converting List to RxList and using refresh() do the magic.
Change
late final List<FoodCategory> foodList;
into
late final RxList<FoodCategory> foodList;
After updating the item, add Your_RxList_Variable.refresh()
.
void addFood(index, food) {
foodList[index].foods.add(food);
foodList.refresh();
}