Reputation: 183
I've searched a lot on the internet but couldn't find the exact solution. How to get a list of selected Chips items
I am passing the list of the object for option list values but unable to get the index of the selected item in onChanged
method
Container(
child: FormField<List<Hashtag>>(
autovalidate: true,
initialValue: hashtagSelectedList,
onSaved: (value) {
Utility.showToast(value.toString());
//hashtagSelectedList[0].hashtag = value.toString();
},
validator: (value) {
if (value.isEmpty) {
return 'Please select some categories';
}
if (value.length > 5) {
return "Can't select more than 5 categories";
}
return null;
},
builder: (state) {
return Column(
children: <Widget>[
Container(
alignment: Alignment.centerLeft,
child: ChipsChoice<Hashtag>.multiple(
value: state.value,
options: ChipsChoiceOption.listFrom<Hashtag, Hashtag>(
source: _hashtags,
value: (i, v) => v,
label: (i, v) => v.hashtag.toString(),
),
onChanged: (val) {
if (val.length > 5) {
Utility.showToast(
"Can't select more than 5 categories");
return;
}
state.didChange(val);
},
itemConfig: ChipsChoiceItemConfig(
showCheckmark: false,
selectedColor: Colors.indigo,
selectedBrightness: Brightness.dark,
unselectedColor: Colors.indigo,
unselectedBorderOpacity: .3,
),
isWrapped: true,
),
),
Container(
padding: EdgeInsets.fromLTRB(15, 0, 15, 15),
alignment: Alignment.centerLeft,
child: Text(
state.errorText ?? state.value.toString(),
style: TextStyle(
color: state.hasError
? Colors.redAccent
: Colors.green),
)),
],
);
},
),
),
Option list - List<Hashtag> _hashtags;
Initial list - List<Hashtag> hashtagSelectedList;
Model -
class Hashtag {
int id;
String hashtag;
int status;
bool isSelected = false;
Hashtag();
Hashtag.fromJson(Map<String, dynamic> json) {
id = json[ApiKeys.id] ?? 0;
hashtag = json[ApiKeys.hashtag] ?? '';
status = json[ApiKeys.status] ?? 0;
}
}
Please give me solutions
Upvotes: 0
Views: 3771
Reputation: 1609
Abhijit Rajmane Try this for your case:
List<Category> _selectedCats = [];
List<Category> _categories = [
new Category(id: "001", name: "Cat 001"),
new Category(id: "002", name: "Cat 002"),
new Category(id: "003", name: "Cat 003"),
];
Widget for the given categories:
Container(
child: ChipsChoice<Category>.multiple(
value: _selectedCats,
options: ChipsChoiceOption.listFrom<Category, Category>(
source: _categories,
value: (i, v) => v,
label: (i, v) => v.name,
),
onChanged: (val) {
//val.forEach((category) {
// print("${category.id} - ${category.name}");
//});
setState(() => _selectedCats = val);
}),
)
For more example refer to the chips_choice package examples.
Hope this will help.
Upvotes: 1