ChoiceChip get unselected strangely
Hi davigmacode, thank you for this sweet package😊. I've been utilizing the package you provided recently and noticed an interesting observation. In one of our projects, we incorporated ChoiceChip widgets both with and without the choice package. We found that when a ChoiceChip implemented without the choice package was selected, it inadvertently deselected other ChoiceChips implemented with the choice package. This behavior piqued my curiosity, prompting me to reach out to you for clarification.
Hi evanse9, Much appreciated! Would you mind sharing your code so I can learn from it?
Hi, we were able to resolve the problem. I uploaded 3 images were you can see the List we created, the original Choice.inline widget code and the modified Choice.inline code. In the original code, we used the prewritten methods provided by the Choice package at the level of the 'selected' and 'onselected' properties which is "selected: selection.selected(_c_k[i]), onSelected: selection.onSelected( _c_k[i], ),"
but in the modified(fixed) version we created a variable (Selected_car_K) which can hold a certain string and compare it's value to the name(text written on the choice chip) of the choice chip, and if the names are the same, the state of that choice chip is changed and it get selected. This is the code " selected: Selected_car_K == _c_k[i].K_name , onSelected: (value) { setState(() { Selected_car_K = value ? _c_k[i].K_name.toString() : 'all' ; }); }," So i think the problem was at the level of the state management or the prewritten select method called at the level of the properties 'selected' and 'onselected' or may be i implemented the widget wrongly.
I see! To manage the selected value in your choice widget, you have two approaches:
-
Updating from outside the widget:
Use the
onChangedparameter to define a callback function that receives the newly selected value. This function can then update yourselectedValuevariable accordingly. -
Setting the initial value inside the widget:
Set the
valueparameter directly to yourselectedValuevariable. This will automatically populate the widget with the current selection.
Here's a code example that demonstrates both approaches:
InlineChoice<String>.single(
clearable: true,
value: selectedValue, // Set initial value
onChanged: (newValue) { // Handle value changes from outside
setState(() {
selectedValue = newValue;
});
},
itemCount: choices.length,
itemBuilder: (state, i) {
return ChoiceChip(
selected: state.selected(choices[i]),
onSelected: state.onSelected(choices[i]),
label: Text(choices[i]),
);
},
),