Flutter

Flutter, Validation for autocomplete textfields

Recently I started developing an android app using flutter and required an autocomplete field. I used this package, which seem to be quite popular: https://pub.dev/packages/autocomplete_textfield

There was just one problem: validation won't work out of the box with this one. It requires to be wrapped in a FormField to enable validation rules. Unfortunately this isn't enough, since the decoration won't update after the initial draw. Digging around in the issues on github if found an updateDecoration() function, which seems to be able to update a few more things than the decoration. Calling this one only works when there is a state in the current key, which was a pitfall for me. In the end I came up with this quite simple class:

import 'package:autocomplete_textfield/autocomplete_textfield.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

class SimpleAutoCompleteTextFormField extends FormField<String> {

  SimpleAutoCompleteTextFormField({
    FormFieldValidator<String> validator,
    String initialValue,
    GlobalKey<AutoCompleteTextFieldState<String>> automcompleteKey,
    List<String> suggestions,
    TextEditingController controller,
    TextInputType keyboardType = TextInputType.text,
    InputDecoration decoration
  }) : super(
    validator: validator,
    initialValue: initialValue ?? "",
    builder: (FormFieldState<String> state) {

      final InputDecoration effectiveDecoration = (decoration ?? const InputDecoration())
        .applyDefaults(Theme.of(state.context).inputDecorationTheme)
        .copyWith(errorText: state.errorText);

      final autoCompleteField = SimpleAutoCompleteTextField(
        key: automcompleteKey,
        decoration: effectiveDecoration,
        clearOnSubmit: false,
        suggestions: suggestions,
        controller: controller,
        keyboardType: keyboardType,
        textChanged: ,
        textSubmitted: ,
      );

      // if there is a current state, we need to update, creating a new one won't work
      // https://github.com/felixlucien/flutter-autocomplete-textfield/issues/36#issuecomment-507529079
      if(automcompleteKey.currentState != null)
        autoCompleteField.updateDecoration(
          decoration: effectiveDecoration
        );

      return autoCompleteField;
    }
  );
}

I'm not sure if that's the correct way, but it works so far :)

The Code can be found on my gitlab too: https://gitlab.com/snippets/1922929

{{ message }}

{{ 'Comments are closed.' | trans }}