gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 16:10:05 56 4
gpt4 key购买 nike

当我将一个项目添加到 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.
);
}
}

enter image description here

最佳答案

我终于明白了。

将 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 - 更新子列表中的项目不是 react 性的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68249333/

56 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com