Reputation: 35
I have a list like that List itemList = [ IdText(1,'hello'), IdText(2,'hallo'), IdText(3,'ciao') ]; and I want to do a radiolisttile; I show the text and I save the ids in map.But I have an error(selected button not colored), How can I fix this? here is the my code below:
for(IdText list in itemList)
RadioListTile(
title: Text(list.text),
groupValue: _map[item.fieldName],
onChanged: (value) {
setState(() {
_map[item.fieldName] = value.id;
});
print(_map[item.fieldName] );
},
value: list,
),
Upvotes: 2
Views: 2531
Reputation: 1122
You can build a customRadioGroup which takes in your items and handles change.
class CustomRadioGroup extends StatefulWidget {
final Function(IdText) onValueSelected;
final List<IdText> items;
const CustomRadioGroup({Key key, @required this.onValueSelected,this.items})
: super(key: key);
@override
_CustomRadioGroupState createState() => _CustomRadioGroupState();
}
class _CustomRadioGroupState extends State<CustomRadioGroup> {
var selectedValue;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Container(
child: ListView.builder(
itemCount: widget.items.length,
itemBuilder: (context, position) {
return RadioListTile(
title: Text(widget.items[position].text),
groupValue: selectedValue,
onChanged: (value) {
setState(() {
selectedValue = value;
});
widget.onValueSelected(widget.items.firstWhere((element) => element.id==value));
},
value: widget.items[position].id);
}),
));
}
}
Pass the onValueSelected callback function that triggers each time the radiobutton selection is changed.
class MyApp extends StatelessWidget {
final List<IdText> items = [ IdText(1,'hello'), IdText(2,'hallo'), IdText(3,'ciao') ];
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(accentColor: Colors.blue),
home: CustomRadioGroup(onValueSelected: onValueSelected, items: items),
);
}
onValueSelected(value) {
print(value);
}
}
Upvotes: 3