I am using multi_select_flutter
and trying to implement Multi Select Widget in Flutter. I want the widget to preload a list (selectedFonts). I tried using the initialValue argument but it doesn't seem to work the way I want it to. I've been trying to deal with this for quite a long time, I even tried initializing within initState and putting setState().
Column(
children: <Widget>[
MultiSelectBottomSheetField<Font?>(
initialChildSize: 0.7,
maxChildSize: 0.8,
initialValue: selectedFonts,
listType: MultiSelectListType.CHIP,
checkColor: Color.fromARGB(255, 65, 78, 158),
selectedColor: Color.fromARGB(255, 18, 21, 55),
selectedItemsTextStyle: TextStyle(
fontSize: 25,
color: Colors.white,
),
unselectedColor: Colors.greenAccent[200],
buttonIcon: Icon(
Icons.add,
color: Color.fromARGB(255, 255, 255, 255),
),
searchHintStyle: TextStyle(
fontSize: 20,
),
searchable: true,
buttonText: Text(
'FONT', //"????",
style: TextStyle(
fontSize: 18,
color: Colors.grey,
),
overflow: TextOverflow.ellipsis,
maxLines: 5,
),
title: Text(
"Fonts",
style: TextStyle(
fontSize: 25,
color: Colors.pink,
),
),
items: _items,
onConfirm: (values) {
setState(() {
selectedFonts = values;
});
print('selected : ${selectedFonts}');
selectedFonts.forEach(
(item) => item == null ? print('') : print(item));
/*senduserdata(
'partnerreligion', '${selectedFonts.toString()}');*/
},
chipDisplay: MultiSelectChipDisplay(
textStyle: TextStyle(
fontSize: 18,
color: Colors.black,
),
onTap: (value) {
setState(() {
selectedFonts.remove(value);
});
print('removed: ${selectedFonts.toString()}');
},
),
),
selectedFonts == null || selectedFonts.isEmpty
? MultiSelectChipDisplay(
onTap: (item) {
setState(() {
selectedFonts2.remove(item);
print(
'removed below: ${selectedFonts2.toString()}');
});
_multiSelectKey.currentState?.validate();
},
)
: MultiSelectChipDisplay(),
],
),
CodePudding user response:
You can directly assign initialValue
, test this widget
class MulTiSlt extends StatefulWidget {
const MulTiSlt({Key? key}) : super(key: key);
@override
State<MulTiSlt> createState() => _MulTiSltState();
}
class _MulTiSltState extends State<MulTiSlt> {
Gender? selected;
static List<Font> fontList = [
Font(id: 1, name: "A"),
Font(id: 2, name: "B"),
Font(id: 3, name: "C"),
Font(id: 4, name: "D"),
];
final _multiSelectKey = GlobalKey<FormFieldState>();
@override
Widget build(BuildContext context) {
return MultiSelectBottomSheetField<Font?>(
key: _multiSelectKey,
initialChildSize: 0.7,
maxChildSize: 0.8,
initialValue: [
fontList[1],
// here include initial values
],
listType: MultiSelectListType.CHIP,
items: fontList
.map(
(animal) => MultiSelectItem(
animal,
animal.name,
),
)
.toList(),
onConfirm: (values) {},
);
}
}
class Font {
final int id;
final String name;
Font({
required this.id,
required this.name,
});
}