Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

dart - Adding and Removing Items From Flutter Lists Dynamically

I have these two functions that should add the item onTap to the list, and then another one to delete the item. The first one (adding the item) works fine, but the delete one doesn't seem to delete anything. I suspect the issue is that the counter variable is not global, but for some reason it doesn't work fine when I add it globally (and I would need it to be). Here's the full code:

List<int> _totalPrice = [];
List<int> get totalPrice => _totalPrice;

here is the add item function

Future getTotal(item) async {
int counter = 0;

_totalPrice.add(int.parse(item));
_totalPrice.forEach((element) => counter += element);

print('LIST: $_totalPrice');
print('SUM: $counter');
return counter;
}

here is the delete function that doesn't remove anything

deleteSumItem(String item) {
_totalPrice.remove(item);
}

I think the issue is that the counter variable isn't global, I am not sure how to add it globally to change dynamically.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

So, here your code shows that you are putting int in your _totalPrice list, but you are trying to remove the String from the list. It will not be found to be deleted.

So, you can change the data type of your list into String or you can write the below function to delete an item where the function only takes an int

deleteSumItem(int item) {
_totalPrice.remove(item);
}

Also you can remove an item by below line of code (If you have a custom type of data in your list):

_totalPrice.removeWhere((item) => item.price == '520')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...