raj*_*alx 2 dart flutter flutter-getx
当我将项目添加到 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");
}
}
Run Code Online (Sandbox Code Playgroud)
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.
);
}
}
Run Code Online (Sandbox Code Playgroud)
我终于想通了。
将List 转换为RxList 并使用refresh() 可以发挥神奇作用。
改变
late final List<FoodCategory> foodList;
Run Code Online (Sandbox Code Playgroud)
进入
late final RxList<FoodCategory> foodList;
Run Code Online (Sandbox Code Playgroud)
更新项目后,添加Your_RxList_Variable.refresh().
void addFood(index, food) {
foodList[index].foods.add(food);
foodList.refresh();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3629 次 |
| 最近记录: |