How to Add Autocomplete Suggestions on TextField in Flutter

In this example, we are going to show you how to add autocomplete suggestions feature on TextField Input in Flutter. It is not exactly a TextField, but using a package, we can have a similar input field with autocomplete suggestions.

List<String> suggestons = ["USA", "UK", "Uganda", "Uruguay", "United Arab Emirates"];
RawAutocomplete(
    optionsBuilder: (TextEditingValue textEditingValue) {
      if (textEditingValue.text == '') {
        return const Iterable<String>.empty();
      }else{
          List<String> matches = <String>[];
          matches.addAll(suggestons);

          matches.retainWhere((s){
            return s.toLowerCase().contains(textEditingValue.text.toLowerCase());
          });
          return matches;
      }
    },

    onSelected: (String selection) {
        print('You just selected $selection');
    }, 

    fieldViewBuilder: (BuildContext context, TextEditingController textEditingController,
        FocusNode focusNode,
        VoidCallback onFieldSubmitted) {
          return TextField(
            decoration: InputDecoration(
               border: OutlineInputBorder()
            ),
            controller: textEditingController,
            focusNode: focusNode,
            onSubmitted: (String value) {
            
            },
          );
    },

    optionsViewBuilder: (BuildContext context, void Function(String) onSelected, 
                         Iterable<String> options) { 
        return Material(
          child:SizedBox(
            height: 200,
            child:SingleChildScrollView(
              child: Column(
                children: options.map((opt){
                  return InkWell(
                    onTap: (){
                       onSelected(opt);
                    },
                    child:Container(
                        padding: EdgeInsets.only(right:60),
                        child:Card(
                            child: Container( 
                              width: double.infinity,
                              padding: EdgeInsets.all(10),
                              child:Text(opt),
                            )
                        )
                    )
                  );
                }).toList(),
              )
            )
          )
        );
    },
)

Output:

 List<String> suggestons = ["USA", "UK", "Uganda", "Uruguay", "United Arab Emirates"];
Autocomplete(
  optionsBuilder: (TextEditingValue textEditingValue) {
    if (textEditingValue.text == '') {
      return const Iterable<String>.empty();
    }else{
        List<String> matches = <String>[];
        matches.addAll(suggestons);

        matches.retainWhere((s){
           return s.toLowerCase().contains(textEditingValue.text.toLowerCase());
        });
        return matches;
    }
  },
  onSelected: (String selection) {
      print('You just selected $selection');
  },
)

Output:

You need to add flutter_typeahead Flutter package in your project by adding the following lines in pubspect.yaml file:

dependencies:
  flutter:
    sdk: flutter
  flutter_typeahead: ^3.2.3

import 'package:flutter_typeahead/flutter_typeahead.dart';
 List<String> suggestons = ["USA", "UK", "Uganda", "Uruguay", "United Arab Emirates"];
TypeAheadField(
    animationStart: 0,
    animationDuration: Duration.zero,
    textFieldConfiguration: TextFieldConfiguration(
      autofocus: true,
      style: TextStyle(fontSize: 15),
      decoration: InputDecoration(
        border: OutlineInputBorder()
      )
    ),
    suggestionsBoxDecoration: SuggestionsBoxDecoration(
        color: Colors.lightBlue[50]
    ),
    suggestionsCallback: (pattern){
        List<String> matches = <String>[];
        matches.addAll(suggestons);

        matches.retainWhere((s){
          return s.toLowerCase().contains(pattern.toLowerCase());
        });
        return matches;
    },
    itemBuilder: (context, sone) {
      return Card(
          child: Container( 
            padding: EdgeInsets.all(10),
            child:Text(sone.toString()),
          )
      );
    },
    onSuggestionSelected: (suggestion) {
        print(suggestion);
    },
)

import 'package:flutter/material.dart';
import 'package:flutter_typeahead/flutter_typeahead.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
     return MaterialApp(
        home: Home()
      );
  }
}

class Home extends  StatefulWidget {
  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  List<String> suggestons = ["USA", "UK", "Uganda", "Uruguay", "United Arab Emirates"];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
         appBar: AppBar(
            title: Text("Autocomplete on TextField"),
            backgroundColor: Colors.redAccent
         ),
          body: Container(
             margin: EdgeInsets.all(30),
             alignment: Alignment.topCenter,
             child: Column(
                 children: [
                      TypeAheadField(
                          animationStart: 0,
                          animationDuration: Duration.zero,
                          textFieldConfiguration: TextFieldConfiguration(
                            autofocus: true,
                            style: TextStyle(fontSize: 15),
                            decoration: InputDecoration(
                              border: OutlineInputBorder()
                            )
                          ),
                          suggestionsBoxDecoration: SuggestionsBoxDecoration(
                              color: Colors.lightBlue[50]
                          ),
                          suggestionsCallback: (pattern){
                              List<String> matches = <String>[];
                              matches.addAll(suggestons);

                              matches.retainWhere((s){
                                return s.toLowerCase().contains(pattern.toLowerCase());
                              });
                              return matches;
                          },
                          itemBuilder: (context, sone) {
                            return Card(
                               child: Container( 
                                  padding: EdgeInsets.all(10),
                                  child:Text(sone.toString()),
                               )
                            );
                          },
                          onSuggestionSelected: (suggestion) {
                             print(suggestion);
                          },
                        )
                 ],
             ),
          )
      );
  }
}

In this way, you can add Autocomplete Suggestion on TextField input in Flutter App.

No any Comments on this Article


Please Wait...