我尝试使用 GetBuilder 更新状态,但无法正常工作。如果我执行热重载,新对象在列表中可见,但页面未填充新项目。我应该重新加载页面还是应该使用响应式 Observable?此外,当我尝试使用 foodList.obs 使食物列表可观察时 - 我收到错误,因为我无法使食物类型对象可观察。很奇怪。
class FoodsController extends GetxController {
List<Food> foodList = [];
int nrOfFoods;
onInit() {
foodList.add(Food(name: 'banana', type: 'fruits'));
foodList.add(Food(name: 'apples', type: 'fruits'));
foodList.add(Food(name: 'melon', type: 'fruits'));
super.onInit();
}
@override
void onReady() {
nrOfFoods.obs;
super.onReady();
}
void addItem(Food item) {
foodList.add(item);
nrOfFoods = foodList.length;
update();
}
}
class HomePage extends StatelessWidget {
FoodsController foodsController = Get.put(FoodsController());
@override
Widget build(BuildContext context) {
print(foodsController.foodList);
return Scaffold(
appBar: AppBar(
title: Text('App Bar'),
),
body: Column(
children: [
Expanded(
child: GetBuilder<FoodsController>(
init: FoodsController(),
builder: (_) => ListView.builder(
itemCount: foodsController.foodList.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(foodsController.foodList[index].name));
},
),
),
),
FloatingActionButton(
child: Text("test"),
onPressed: () => {
foodsController.foodList.add(Food(name: "chicken", type: "meat")),
Get.to(SecondPage())
},
),
],
),
);
}
}
谢谢