Adding and Removing Items From Flutter Lists Dynamically - flutter

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.

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')

Related

How to create a method inside a provider class

I want to be clear and precise. I have a database with 260 variables, I have a data model class and a SQLiteHelper class. I'm using a provider and I have all the CRUD inside.
The problem comes because I have scrolleable page in which I want to be able to change all variables. Around 240 variables are int? and each one will have a button which do the same, convert it to zero if it is null or add 1 if it is an integer. I'm not using a normal callback because in that scrolleable page I use different reusable buttons and I want to know the value of the variable in child and parent widget. In the reusable buttons for change color and text, and in the parent widget(scrolleable page) to save them in SQlite at the end of the page with a save button.
This is my provider class
class DBProvider with ChangeNotifier {
final SQLiteHelper0 _db = SQLiteHelper0();
List<DB> _items = [];
Future<void> loadDB() async {
List<Map<String, dynamic>> data = await _db.charDB;
_items = data.map((DB) {
return DB(
id: charDB["id"],
name: charDB["name"],...// the rest of the CRUD
I'm trying something like that
dynamic increment(index){
if(_items[index] != int?){
return _items[index];
} else if (_items[index]! == null){
return _items[index]== 0;
}else { return _items[index] + 1;}
}
an then in the scrolleable page make another function like that
late DBProvider _dBProvier;
void _increment(index){setState(() {
_dBProvider.increment(index);
});}
I am having different problems, at times I think that nothing makes sense. But if it is a totally dumb way, please give me some direction to keep trying. This question is related with other question where I focused the problem in a different and wrong way Why this function is null?
Thanks.

value of my List is changing when i delete text from TextField Flutter

i have a list that i want to search in (I remove the values that don't match my search), I write the search word in a TextField and save the initial list in order to show it again when the user deletes the search word (or want to search for another thing) .
i can save the list in a variable but the issue is when I start deleting the search word the value of my initial list becomes the same that the list I show for the search !
onChanged: (val) {
//i save the list before doing any change here
if (_initList == null) _initList = myList;
// this part works fine
if (val.length > 2)
setState(() {
myList.removeWhere((element) => !element
.getName()
.toLowerCase()
.contains(val.toLowerCase()));
});
// when i’m in the else, when i try to print _initList value i find that it’s the same as myList
// the value of _initList is not changing anywhere else in the code
else {
setState(() {
myList = _initList;
});
}
},
when you do this
if (_initList == null) _initList = myList;
both variables will point to the same list. changes to one list will also change the other, because they are in fact the same list. What you want to do is safe a copy of the list in it. You can do it by calling toList() on it, like
if (_initList == null) _initList = myList.toList();

Issue With Adding and Deleting Function in Flutter

I have these two functions that should add and remove the item on the list. The adding one should also calculate the total sum of all items, but it doesn't work quite exactly as it should. Here is the adding function:
Future getTotal(item) async {
int counter = 0;
counter += int.parse(item);
totalPrice.add(counter);
_totalPrice.forEach((element) => counter += element);
print(totalPrice);
print(counter);
return totalPrice;
}
It first declares counter (which is sum basically), then it should onTap calculate the total sum of all items, but I get this problem, where it adds items properly, but the counter adds one extra item on the first tap, like the counter is added twice in the beginning, I suspect this code is the issue:
counter += int.parse(item);
totalPrice.add(counter);
Here is the issue in pictures:
Now for the delete function
I have this simple delete function, but it doesn't seem to remove any item onTap:
deleteSumItem(item) {
_totalPrice.remove(item);
notifyListeners();
print(totalPrice);
}
It should work together with the getTotal(item) function, removing the particular item from it, but as I mentioned, it doesn't seem to do anything, and returns full list each tap.
I hope I was clear, I never seem to figure out the simple issues. Thank you!
You are adding the element twice here: _totalPrice.forEach((element) => counter += element);
with regards to removing, you are using (mainly) totalPrice when adding but _totalPrice when removing. See the difference?

Dynamic choice of variable by a function in Dart (Flutter)

I am building my first app with Flutter, here's the problem I stuck with:
I have several tabs with radio buttons, the tabs are generated dynamically. I am using two functions to handle the changes in those radio buttons. Each function is used in every tab.
My problem is that I don't know how to assign the value of the radio buttons to different variables.
I precreated the variables, but how do I access them from my functions? I tried do do it this way:
var bedsRoom1, bedsRoom2... bedsRoom7; //7 variables which is maximum of what I need
I use the functions as a callback inside the state of the stateful widget. Inside the function I tried to do:
void _handleRadioValueChange1(int value, int counter) {
setState(() {
_radioValue1 = value;
bedsRoom$counter = value;
});
}
I get error messages about an undefined name of a variable. Please explain how to do it right.
Instead of declaring multiple variables, you can declare a list of variables like this -
List bedRooms = new List(7);
Then you can access the variables like this -
void _handleRadioValueChange1(int value, int counter) {
setState(() {
_radioValue1 = value;
bedsRooms[counter] = value;
});
}
You can read more about List in dart from here -
Lists in dart

Knockoutjs nested view model updates

I'm trying to understand how I can have nested knockoutjs view models with a little fiddle that lists some items and on click of a button, it shows the details of that item. Then, I have a button that updates the Id property of each item by adding 15 to each ones but for a reason, they end up having all the same value at the end.
Can someone enlighten me?
Thanks!
The fiddle in question
It's your .Name computed property. The Id change works correctly.
http://fiddle.jshell.net/Y3JXD/1/
The item in the closure was always the last item in the list after the first execution. Remember that the computed is updated any time the observable changes. So, the first time during setup, it worked fine as item was the item from the loop. But, what was captured in the closure was just item (the 15th item), not the one that was for that specific loop instance.
Update: forgot about the second parameter to computed as suggested in a comment.
http://fiddle.jshell.net/Y3JXD/1/
item.Name = ko.computed(function () { return 'Item_' + item.Id(); }, item);
Here's another technique for wrapping the reference in a closure, and capturing the right item instance (just as a demonstration for what needs to happen to capture the proper scope).
self.loadItems = function () {
for (var i = 0; i < 15; i++) {
var item = ko.mapping.fromJS({
Id: i
});
self.items.push(item);
(function (item) {
item.Name = ko.computed(function () {
return 'Item_' + item.Id();
});
})(item);
}
};
Could you move the Name property to the itemModel?
self.Name = ko.computed(function() {
return 'Item_' + self.Id();
});
It seems odd to set it when you create the object, rather than when you consume it.