Autocomplete List is not updating after removing item?

25 Views Asked by At

I am using the AutoComplete in flutter to make it searchable but the list is not updating after removing the item from the list instantly on the UI/suggestion window.

Autocomplete<String>(
  optionsBuilder: (TextEditingValue textEditingValue) {
    return items
        .where((String option) => option
            .toLowerCase()
            .contains(textEditingValue.text.toLowerCase()))
        .toList();
  },
  onSelected: (String selection) {
    setState(() {
      _addItem(selection);
    });
  },
  fieldViewBuilder: (BuildContext context,
      TextEditingController textEditingController,
      FocusNode focusNode,
      VoidCallback onFieldSubmitted) {
    return TextField(
      controller: textEditingController,
      focusNode: focusNode,
      onChanged: (value) {
        _addItem(value);
      },
      decoration: const InputDecoration(
        labelText: 'Search',
        border: OutlineInputBorder(),
      ),
    );
  },
  optionsViewBuilder: (BuildContext context,
      AutocompleteOnSelected<String> onSelected,
      Iterable<String> options) {
    return Align(
      alignment: Alignment.topLeft,
      child: Material(
        elevation: 4.0,
        child: Container(
          height: 200.0,
          width: 200,
          child: ListView.builder(
            itemCount: options.length,
            itemBuilder: (BuildContext context, int index) {
              final option = options.elementAt(index);
              return Row(
                mainAxisAlignment:
                    MainAxisAlignment.spaceBetween,
                children: [
                  GestureDetector(
                    child: Text(option),
                    onTap: () {
                      onSelected(option);
                    },
                  ),
                  GestureDetector(
                    child: const Icon(Icons.cancel),
                    onTap: () {
                      _removeItem(option);
                    },
                  ),
                ],
              );
            },
          ),
        ),
      ),
    );
  },
),

functions are

void _addItem(newItem) {
  print("newItem " + newItem.toString());

  setState(() {
    if (newItem.trim().length > 3) {
      if (!items.contains(newItem.trim())) {
        if (items.isEmpty || items.length < 5) {
          setState(() {
            items.add(newItem);
          });
        } else {
          setState(() {
            items.removeAt(0);
            items.add(newItem);
          });
        }
        print("item added = " + items.toString());
      }
    }
  });
}

void _removeItem(value) {
  setState(() {
    if (items.isNotEmpty) {
      items.remove(value);
      print("items removed = " + items.toString());
    }
  });
}

Searching and adding is working fine but the main issue in updating the UI of suggestion.

0

There are 0 best solutions below