Using signals I have a ListView
that is backed by a ListSignal
.
Adding and removing from this list is correctly rebuilding the ListView
and adding new elements as expected. However I’m struggling to find a way to update the contents of one of these elements when the backing object is updated.
class ScannedProduct {
final String name;
final int quantity;
ScannedProduct({required this.name, required this.quantity});
}
class MyCard extends StatelessWidget {
final ScannedProduct product;
MyCard({required this.product});
Widget build(BuildContext context) {
return Card(
child: Row(
children: [
Text(product.name),
Text(product.quantity.toString())
]
)
);
}
}
class MyScreen extends StatefulWidget<_MyScreenState> {
//omitted for brevity
}
class _MyScreenState extends State<MyScreenState> {
ListSignal<ScannedProduct> products = ListSignal([]);
Widget build(BuildContext context) {
return ListView.builder(
itemCount: products.length,
itemBuilder: (context, index) => MyCard(
product: products[index]
)
);
}
}
Given the above setup, the below triggers a rebuild as expected
products.add(ScannedProduct('SomeProduct', 1));
How can I trigger a similar update when running the following
products[0].quantity++;
2
Answers
I think it’s easier to create a controller and then mutate the list in the controller. You can then call the method from your UI.
Something like this below:
you can use flutter built in class
ChangeNotifier
and wrap the widget that listen to any operation you specify withListenableBuilder
. all you need to do is callnotifyListeners()
.lets take look at example below :