Home > Enterprise >  Padding in Autocomplete Text field Flutter
Padding in Autocomplete Text field Flutter

Time:06-29

I try to set a padding for the text in an autocomplete field. I did it with a normal Text field like this:

 TextFormField(
            decoration: const InputDecoration(
              border: UnderlineInputBorder(),
              contentPadding: EdgeInsets.only(left: 12.0),
            ),

But I'm not able to do something like this on the autocomplete field.

class AutocompleteField extends StatelessWidget {
  const AutocompleteField({Key? key}) : super(key: key);

  static const List<String> _kOptions = <String>[
    'Superdry',
    'H&M',
  ];

  @override
  Widget build(BuildContext context) {
    return Autocomplete<String>(
      optionsBuilder: (TextEditingValue textEditingValue) {
        if (textEditingValue.text == '') {
          return const Iterable<String>.empty();
        }
        return _kOptions.where((String option) {
          return option.contains(textEditingValue.text.toLowerCase());
        });
      },
      onSelected: (String selection) {
        debugPrint('You just selected $selection');
      },
    );
  }
}

enter image description here

The above field is the autocomplete and I want that it looks like the lower image. Do you have any suggestions? Thank you!

CodePudding user response:

You can use fieldViewBuilder for that. Something like this:

  @override
  Widget build(BuildContext context) {
    return Autocomplete<String>(
      optionsBuilder: (TextEditingValue textEditingValue) {
        if (textEditingValue.text == '') {
          return const Iterable<String>.empty();
        }
        return _kOptions.where((String option) {
          return option.contains(textEditingValue.text.toLowerCase());
        });
      },
      fieldViewBuilder: (BuildContext context, 
                         TextEditingController textEditingController,
                         FocusNode focusNode,
                         VoidCallback onFieldSubmitted) {
          return TextFormField(
            controller: textEditingController,
            focusNode: focusNode,
            onFieldSubmitted: (str) => onFieldSubmitted(),
            decoration: const InputDecoration(
              border: UnderlineInputBorder(),
              contentPadding: EdgeInsets.only(left: 12.0),
            )
          );
      },
      onSelected: (String selection) {
        debugPrint('You just selected $selection');
      },
    );
  }
  • Related