Flutter Getx - 更新子列表中的项目不是反应性的

Posted

技术标签:

【中文标题】Flutter Getx - 更新子列表中的项目不是反应性的【英文标题】:Flutter Getx - Updating item in children list is not reactive 【发布时间】:2021-07-04 22:48:40 【问题描述】:

当我将一个项目添加到 obs 子列表时,小部件没有更新。 如果我将一个项目添加到主列表,它工作正常。

请帮助我正确实现响应式。

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

【问题讨论】:

【参考方案1】:

我终于想通了。

将 List 转换为 RxList 并使用 refresh() 来发挥作用。

改变

late final List<FoodCategory> foodList; 

进入

late final RxList<FoodCategory> foodList; 

更新项目后,添加Your_RxList_Variable.refresh()

void addFood(index, food) 
    foodList[index].foods.add(food);
    foodList.refresh();

【讨论】:

以上是关于Flutter Getx - 更新子列表中的项目不是反应性的的主要内容,如果未能解决你的问题,请参考以下文章

Flutter GetX 状态管理不起作用

Flutter:如何使用 Getx Obx 更新标记在谷歌地图中的位置?

对 Flutter 应用程序的 getX dart 包中的 RxList 进行排序

即使收到更新的数据,Flutter ListView.builder 的 UI 也不会被 getx 更新

Flutter:Getx Controller中的异步函数在初始化时不起作用

网页中的 Flutter GetX 路由