updateMultiselectValues method

void updateMultiselectValues(
  1. String id,
  2. List<MultiselectOption> newValue, {
  3. bool multiselect = false,
})

Implementation

void updateMultiselectValues(String id, List<MultiselectOption> newValue,
    {bool multiselect = false}) {
  final reference = findMultiselectValueIndex(id);

  if (reference != null) {
    // Lets do some massaging to the values to see if we need to remove some items based on this list.

    // Lets subtract any values that are already stored, and then add any values which should be added.
    final listToRemove = newValue
        .where((value) => multiselectValues[reference]
            .values
            .any((existingValue) => existingValue.value == value.value))
        .toList();

    final updatedValue = [
      // Any Additional new values minus the ones which we removed.
      ...newValue.where((value) =>
          !listToRemove.any((removeVar) => removeVar.value == value.value)),
      // original values minus the values we should be removing (because they were selected again)
      ...multiselectValues[reference].values.where((value) =>
          !listToRemove.any((removeVar) => removeVar.value == value.value)),
    ];

    multiselectValues[reference] = MultiselectFormFieldValueById(
        id: id,
        values: multiselect
            ? updatedValue
            : updatedValue.isNotEmpty
                ? [updatedValue.first]
                : []);
  } else {
    multiselectValues = [
      MultiselectFormFieldValueById(
          id: id,
          values: multiselect
              ? newValue
              : newValue.isNotEmpty
                  ? [newValue.first]
                  : [])
    ];
  }

  notifyListeners();
}