Flutter raw autocomplete suggestions get hidden under soft keyboard

Viewed 473

I'm creating a raw auto complete widget. The issue is if the widget is at the center or around the bottom of the screen, when I start typing the auto suggestions shown gets hidden under the soft keyboard. How to build the optionsViewBuilder to overcome the hiding of the options under the keyboard?

Sample source code:

class AutoCompleteWidget extends StatefulWidget {

  const AutoCompleteWidget(
    Key key,
  ) : super(key: key);

  @override
  _AutoCompleteWidgetState createState() => _AutoCompleteWidgetState();
}

class _AutoCompleteWidgetState extends State<AutoCompleteWidget> {
  late TextEditingController _textEditingController;
  String? _errorText;
  final FocusNode _focusNode = FocusNode();
  final GlobalKey _autocompleteKey = GlobalKey();
  List<String> _autoSuggestions = ['abc', 'def', 'hij', 'aub', 'bted' 'donfr', 'xyz'];

  @override
  void initState() {
    super.initState();
    _textEditingController = TextEditingController();
  }

  @override
  void dispose() {
    _textEditingController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return RawAutocomplete<String>(
      key: _autocompleteKey,
      focusNode: _focusNode,
      textEditingController: _textEditingController,
      optionsBuilder: (TextEditingValue textEditingValue) {
        if (textEditingValue.text == '') {
          return _autoSuggestions;
        }
        return _autoSuggestions.where((dynamic option) {
          return option
              .toString()
              .toLowerCase()
              .startsWith(textEditingValue.text.toLowerCase());
        });
      },
      optionsViewBuilder: (BuildContext context,
          AutocompleteOnSelected<String> onSelected, Iterable<String> options) {
        return Material(
          elevation: 4.0,
          child: ListView(
            children: options
                .map((String option) => GestureDetector(
                      onTap: () {
                        onSelected(option);
                      },
                      child: ListTile(
                        title: Text(option),
                      ),
                    ))
                .toList(),
          ),
        );
      },
      fieldViewBuilder: (
        BuildContext context,
        TextEditingController textEditingController,
        FocusNode focusNode,
        VoidCallback onSubmitted,
      ) {
        return Card(
          elevation: (null == _errorText ? 8 : 0),
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0)),
          child: TextField(
            controller: textEditingController,
            focusNode: focusNode,
          ),
        );
      },
    );
  }
}
1 Answers

A solution I came up with was using was building my own version of a simple autocomplete widget using a TextFormField and setting scrollPadding on it. I'm showing the results in a container with a set height that works with that padding.

  @override
  Widget build(BuildContext context) {
    return ListView(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      children: [
        // THE AUTOCOMPLETE INPUT FIELD
        TextFormField(
          focusNode: _focusNode,
          scrollPadding: const EdgeInsets.only(bottom: 300),
          maxLines: null,
          key: const ValueKey('company_address'),
          autocorrect: false,
          enableSuggestions: false,
          controller: widget.textEditingController,
          validator: (value) {
            if (value!.isEmpty) {
              return _i10n.enterAName;
            }
            return null;
          },
          decoration: InputDecoration(
            labelText: widget.labelText,
          ),
          textInputAction: TextInputAction.next,
          onChanged: (_) {
            _handleChange();
            widget.onChange();
          },
          onTap: () {
            setState(() {
              _showAutocompleteSuggestions = true;
            });
          },
        ),
        const SizedBox(
          height: 5.0,
        ),
        // THE AUTOCOMPLETE RESULTS
        if (_showAutocompleteSuggestions)
          Container(
            // height: _autocompleteHeight,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10),
              boxShadow: const [
                BoxShadow(blurRadius: 10.0, color: Colors.black12)
              ],
              color: Colors.white,
            ),
            constraints: const BoxConstraints(maxHeight: 200.0),
            child: Scrollbar(
              child: SingleChildScrollView(
                child: Column(children: [
                  if (_autocompleteSuggestions.isEmpty)
                    const ListTile(
                      title: Text('No results'),
                    )
                  else
                    ..._autocompleteSuggestions.map((_autocompleteSuggestion) =>
                        Material(
                          child: InkWell(
                            onTap: () {
                              _handleSelectSuggestion(_autocompleteSuggestion);
                            },
                            child: ListTile(
                              leading: const Icon(Icons.location_on_outlined),
                              title: Text(_autocompleteSuggestion.description),
                            ),
                          ),
                        ))
                ]),
              ),
            ),
          ),
      ],
    );
  }

Forgive the quick code dump.

Related