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
Related
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.
I'm making a reactive model with Getx on a product list, but when I start the list it comes with no value and causes an index error even though there are actually values in the list it appears empty at first, which somehow gets fixed automatically. (this is inside a build of a statelesswidget)
return GetX<CartController>(
init: CartController(),
builder: (controller) {
try {
return Text(
"${StringConvert.toMoney(controller.totalByProduct[productId])}",
style: kSmallTextBold,
);
} catch (e) {
return const Text("Error...");
}
},
);
}
I did try catch to manage this, but the catch part doesn't show up;
this is relevant part of the controller
var totalByProduct = [].obs;
fetchTotal() {
List products = storage.read(StorageKeys.cartProducts);
double currentValue = 0.0;
List currentTotals = [];
for (var item in products) {
currentTotals.add(item['total'] * item['amount']);
currentValue += item['total'] * item['amount'];
}
total.value = currentValue;
totalByProduct.value = currentTotals;
}
I believe it's not the right way to do this, so what do I need to know to fix this correctly?
If helps this is the error:
With a method to read the storage (sharedPreferences) in async mode, with a FutureBuilder it was possible to correct the error, because in the initial state the list takes the value assigned explicitly. Even if it then receives the correct value, accessing the index in its initial state causes the error, this explains why even with the error it works.
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')
I have variable called to totalQuantity in provider:
get totalQuantity => total_quantity();
total_quantity() {
var totalQty = 0;
for (var x in myCart) {
totalQty += (x.quantity);
}
return totalQty;
}
I use it in the app bar:
child: Text('${prod.totalQuantity}',
I have a logout function I want when I pressed on it to reset totalQuantity, I guess using setter for that in provider, but I don't know how to do that.
IconButton(
onPressed: () {
prod.clear_myCart();
loginProd.log_out();
// ----------------- I want to reset it here
},
I found my mistake ,I forgot to add listen notifier
void clear_myCart() {
myCart.clear();
notifyListeners();
}
after I add it ,it works fine
I understand that you want to return totalQuantity to the original (empty) value, so lets have a look at where it gets its value from:
Your total_quantity() function depends on one variable, myCart.
So, if you clear myCart in prod.clear_myCart();, the quantity should also be updated accordingly.
Now, what your code does not show is how the value change of myCart is being handled in your code;
I am speculating here because your code snippets don't provide enough information, but your ChangeNotifier might just not call notifyListeners() when you call prod.clear_myCart(); (See https://flutter.dev/docs/development/data-and-backend/state-mgmt/simple).
I can't find a simple way to update a series of variables in my Flutter project.
I first tried using Enums and functions to change the variables inside a setState((){}) call.
I have something like this:
void changeMode(Mode mode) {
if (mode == Mode.start) {
print('App is now in start mode');
mode = Mode.start;
bool1 = true;
bool2 = false;
bool3 = false;
color1 = kAColor1;
color2 = kAColor2;
} else if ...}
But nothing gets updated, I imagine it's due the fact that my function doesn't return anything.
If I hard code every single variable in setState((){}) it works fine, but it's absolutely inefficient and a mess to correct.
Maybe I should go with classes? Would I need to create a superclass containing all the subclasses to do something like this?
Every time that you call setState you UI will rebuild. You can use class or map to manipulate your data.
With class:
setState(() {
currentData = actualData.copyWith(bool1: false)
})
This way, you change only data that is different from currentData. On this example, I maintain all information from currentData and change only bool1 value.
Obs: copyWith is a factory that return the same type of
currentData.