Flutter GetX List 变化界面不更新?使用 Obx 和 update() 解决
如果你已经使用了 'Obx' 来监听 'Getx List' 的变化,但是界面没有发生变化,可能是因为没有使用 'update()' 方法来通知 'Getx' 更新界面。
可以在 'List' 上使用 'obs' 来将其转换为可观察的对象,然后在 'Obx' 中使用 'value' 属性来获取 'List' 的值,并在需要更新界面的地方调用 'update()' 方法。
以下是一个示例代码:
import 'package:flutter/material.dart';
import 'package:get/get.dart';
class MyController extends GetxController {
var mylist = [].obs;
void addItem(String item) {
mylist.add(item);
}
}
class MyPage extends StatelessWidget {
final MyController controller = Get.put(MyController());
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('My Page'),
),
body: Center(
child: Obx(
() => ListView.builder(
itemCount: controller.mylist.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(controller.mylist[index]),
);
},
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
controller.addItem(DateTime.now().toString());
controller.update();
},
child: Icon(Icons.add),
),
);
}
}
在上面的示例中,我们将 'mylist' 转换为可观察的对象,并在 'Obx' 中使用 'value' 属性来获取其值。在添加新项时,我们调用 'update()' 方法来通知 'Getx' 更新界面。
原文地址: https://www.cveoy.top/t/topic/lBlK 著作权归作者所有。请勿转载和采集!