比较2列表并返回索引值为true或false



我有两个来自firebase的项目列表。

final List listOfAnswers = ['Apple','Grape','Watermelon','Strawberry'];
final List selectedAnswers = ['Apple','Watermelon','Strawberry'];

我已经在UI中使用了flutter_multi_select_items包小部件的Checkbox,在该UI中我必须将selectedAnswers显示为已选择。为了做到这一点,我试着创建了很多函数,但都不起作用。

bool getSelectedOptions(QuerySnapshot snapshot) {
bool x = false;
final List listOfAnswers = snapshot.docs[_counter.value]['options'];
final List selectedAnswers =
snapshot.docs[_counter.value]['listOfSelectedOptions'];
final indexes =
listOfAnswers .mapIndexed((index, element) => index).toList();
listOfAnswers .forEachIndexed((index, element) {
for (int i = 0; i < selectedAnswers .length; i++) {
if (element == selectedAnswers [i]) {
print('index: $index, element: $element');
x = true;
} else {
x = false;
}
}
}
});
print(indexes);
return x;
}

以上是众多试验之一。如果两个列表中的项目匹配,请建议一种更好的方法来每次获得true或false bool值。提前感谢

编辑:复选框小部件的代码

MultiSelectCheckList(
textStyles: const MultiSelectTextStyles(
selectedTextStyle:
TextStyle(
color: Colors
.white,
fontWeight:
FontWeight
.bold)),
itemsDecoration: MultiSelectDecorations(
selectedDecoration:
BoxDecoration(
color: Colors
.indigo
.withOpacity(
0.8))),
listViewSettings:
ListViewSettings(
shrinkWrap: true,
separatorBuilder:
(context, index) =>
const Divider(
height: 0,
),
),
controller: _controller,
singleSelectedItem:
false, // if true it will work like radio button
items: List.generate(
optionLength.length,
(index) =>
CheckListCard(
value: mySnapshot
.docs[_counter
.value]
['options']
[index]
.toString(),
title: Text(mySnapshot
.docs[_counter
.value]
['options']
[index]
.toString()),
selectedColor:
Colors.white,
checkColor:
Colors.indigo,
selected:
getSelectedOptions(
mySnapshot),

checkBoxBorderSide:
const BorderSide(
color: Colors
.blue),
shape:
RoundedRectangleBorder(
borderRadius:
BorderRadius
.circular(
5),
),
),
),
onChange:
(allSelectedItems,
selectedItem) {},

),

从你的代码来看,我认为你想要这样的东西:

bool getSelectedOptions(int index, QuerySnapshot snapshot) {
String answer = snapshot.docs[_counter.value]['options'][index];
List selectedAnswers = snapshot.docs[_counter.value]['listOfSelectedOptions'];
return selectedAnswers.contains(answer);
}

并更改

selected:
getSelectedOptions(
mySnapshot),

selected:
getSelectedOptions(index, 
mySnapshot),

最新更新