Reputation: 207
Can someone help me how to update a List in "cart_products.dart" on clicking "addToCart" button from a different dart file(different UI)? Hard coded List is working but I have no idea how to update the List dynamically. It would be a great help for new comers if someone can demonstrate with a simple example. Thank you.
Upvotes: 0
Views: 2777
Reputation: 4783
Use a global list items
In your main.dart file
ValueNotifier itemsNotifier = ValueNotifier([]);
void main() {
// ...
}
Anywhere (different dart file)
List _tmpList = itemsNotifier.value;
_tmpList.add(YOUR_ITEM);
itemsNotifier.value = _tmpList;
Display list items like this
ValueListenableBuilder(
valueListenable: itemsNotifier,
builder: (context, items, _) {
return ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(
title: Text("Item ${index}"),
);
}
);
}
),
Upvotes: 1
Reputation: 3479
suppose you have an existing list like following,
final listItems = [item1,item2, item3];
if you want to add item4 in it, you need to call setState and inside that add logic, like following:
addItemInList(){
setState{
(){
listItems.add(item4);
}
}
}
same applies for deletion and updation.
Upvotes: 0