如何对Flutter MultiSelect下拉框的state.specialityList进行字母排序?调用.sort()报错
解决多选下拉框列表排序报错问题
问题原因
直接调用.sort()报错是因为state.specialityList是自定义对象的列表,并非字符串列表,默认没有排序规则,必须传入自定义比较函数指定排序依据。
解决方案
修改items属性的代码,先对specialityList按content字段的字母顺序排序,再映射为MultiSelectItem。这里推荐使用不区分大小写的排序逻辑(若需要区分大小写可去掉.toLowerCase()):
items: List.from(state.specialityList ?? []) ..sort((a, b) => (a.content as String).toLowerCase() .compareTo((b.content as String).toLowerCase())) .map((e) => MultiSelectItem(e.id, e.content as String)) .toList(),
代码说明
List.from(state.specialityList ?? []):创建原列表的副本,避免原地修改原状态中的列表(防止不必要的状态变更)..sort((a, b) => ...):使用链式调用,对副本列表排序,比较逻辑是基于content字段的字符串比较- 最后映射为
MultiSelectItem生成下拉选项列表
完整修改后的代码片段
ProfileField( child: Container( decoration: BoxDecoration( color: CustomTheme.white, borderRadius: BorderRadius.circular(10.58), border: Border.all( width: 1.25, color: CustomTheme.lightGreen, ), ), child: MultiSelectDialogField( buttonText: Text('Select Specialities'), decoration: BoxDecoration( border: Border.all( color: Colors.transparent, ), ), buttonIcon: Icon( Icons.arrow_drop_down_rounded, color: CustomTheme.deepShadedBlue, size: 24, ), initialValue: state.profile?.speciality ?.map((e) => e as String) .toList() ?? [], items: List.from(state.specialityList ?? []) ..sort((a, b) => (a.content as String).toLowerCase() .compareTo((b.content as String).toLowerCase())) .map((e) => MultiSelectItem(e.id, e.content as String)) .toList(), listType: MultiSelectListType.CHIP, onConfirm: (values) { List<String> specialities = values.map((e) => e as String).toList(); cubit.updateUser(state.copyWith( profile: state.profile?.copyWith(speciality: specialities))); }, ), ), ),
内容的提问来源于stack exchange,提问作者Ronit Banerjee
相关产品推荐
相关产品推荐

