When I click on the button, I need its name to be added to the List
and when the button is clicked again, its name is added to the List
again, but if 2 names match in the List, then they both need to be deleted. I tried to implement through the for loop but it does not work correctly for me. Tell me how can this be done?
function
List<String> types = [];
void reportButton(int number, String type) {
reportsList[number] = !reportsList[number];
if (reportsList.contains(true)) {
isEnabledC = true;
} else {
isEnabledC = false;
}
types.add(type);
for (var element in types) {
if (element == type) {
types.removeWhere((element) => element == type);
}
}
buttons
SizedBox(
width: size.width / 3,
child: GestureDetector(
onTap: () {
cubit.reportButton(0, 'comment');
// state.type = 'comment';
},
child: ReportButton(
enabled: state.reports[0],
svg: constants.Assets.comment,
text: 'Comment',
),
),
),
SizedBox(
width: size.width / 3,
child: GestureDetector(
onTap: () {
cubit.reportButton(1, 'broken');
// state.type = 'broken';
},
child: ReportButton(
enabled: state.reports[1],
svg: constants.Assets.attention,
text: 'Broken station',
),
),
),
CodePudding user response:
you do not have to loop through the list of string. You can simply check if the list contains the string. If yes, remove it, else add the string
List<String> types = ["apple", "ball", "cat", "dog"];
void main() async {
reportButton(1, "xyz");
}
void reportButton(int number, String type) {
if (types.contains(type)) {
types.removeWhere((element) => element == type);
} else {
types.add(type);
}
print(types);
}
CodePudding user response:
List<String> types = ["boy", "girl", "father", "hog"];
void main() {
reportButton(1, "xyz");
}
void reportButton(int number, String type) {
if (types.contains(type)) {
types.removeWhere((element) => element == type);
}else {
types.add(type);
}
print(types);
}