'Why ListView is not refreshed when GetWidget is used as Item of ListView
ListView with GetWidget not updating.
MyItem.dart
class MyItem {
var title = "";
var isChecked = false;
}
MyController.dart
class MyController extends GetxController {
final items = <MyItem>[].obs;
@override
void onReady() {
refresh();
super.onReady();
}
void refresh() async {
var items = <MyItems>[];
for (var i = 0; i < 10; i++) {
var item = MyItem()
..title = i.toString()
..isChecked = i < 3; // Only the first 3 in the list set the check status to true.
items.add(item);
}
this.items.value = items;
}
}
MyPage.dart
class MyPage extends GetView<MyController> {
...
@override
Widget build(BuildContext context) => RefreshIndicator(
onRefresh: controller.onRefresh,
child: Obx(() => ListView.builder(
itemBuilder: (context, i) {
var items = controller.items.value;
var item = items[i];
return MyItemWidget(item: item);
},
itemCount: controller.items.value.length,
)),
);
}
MyItemWidget.dart
class NotificationItem extends GetWidget<MyItemController> {
final MyItem item;
const MyItemWidget({Key? key, required this.item }) : super(key: key);
@override
Widget build(BuildContext context) {
controller.item.value = item;
return Obx(() => InkWell(
child: Container(
width: double.infinity,
height: 50,
color: item.isChecked ? Colors.red : Colors.white,
child : Center(child: Text(item.title))
),
onTap: controller.toggle
));
}
}
MyItemController.dart
class MyItemController extends GetxController {
final item = MyItem().obs;
void toggle() {
item.value.isChecked = !item.value.isChecked;
item.refresh();
}
}
To Reproduce
- Click to list item.
- Check status change.
- pull to refresh.
- Widgets of listview children that are not updated
Expected behavior
When the list is refreshed, the default value of isChecked is true only for the first 3 items in the list, so the first 3 items were expected to change to the checked state, but the widget is not updated.
Instead, when the list is scrolled and moved and then back to position, the build method of Item Widget is called again and drawn on the screen draw to the state.
When using GetX or GetBuilder instead of GetWidget for the items in the list, the didUpdateWidget callback was called and the state could be updated normally. Are these not possible with GetWidget?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
