3 C
New York
Tuesday, November 28, 2023

Flutter Autocomplete example

Flutter 2.0 came out a few days ago and brings us a very useful widget called Autocomplete. With this new friend, we now can quickly implement autocomplete text field without using any third-party plugins. Making a search field with suggestions that appear as the user types something is now neat and easy.

In this article, we will examine a complete example of using the Autocomplete widget in Flutter.Advertisements

Note: This article was recently updated to work properly with the latest versions of Flutter (2.8.1 or newer) and fix some errors related to null safety.

The Example

App Preview

In this example app, the user can enter several characters in the search field to look up some animals. The animals whose names match the characters the user entered will appear in the list of suggestions. The one selected from a list of suggestions will appear in the text widget below.

The code

Here is the full code with explanations in the comments:

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

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

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

  Widget build(BuildContext context) {
    return MaterialApp(
      // Remove the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      theme: ThemeData(
        primarySwatch: Colors.green,
      home: const HomePage(),

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  _HomePageState createState() => _HomePageState();

class _HomePageState extends State<HomePage> {
  // This will be displayed below the autocomplete field
  String? _selectedAnimal;

  // This list holds all the suggestions
  final List<String> _suggestions = [

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Kindacode.com'),
      body: Column(
        children: [
            optionsBuilder: (TextEditingValue value) {
              // When the field is empty
              if (value.text.isEmpty) {
                return [];

              // The logic to find out which ones should appear
              return _suggestions.where((suggestion) =>
            onSelected: (value) {
              setState(() {
                _selectedAnimal = value;
          const SizedBox(
            height: 30,
          Text(_selectedAnimal ?? 'Type something (a, b, c, etc)'),


AdvertisementsThis article has walked you through a full example of implementing the Autocomplete widget. From now on, it will be easier for you to create autocomplete text fields when building apps. If you would like to learn more new and interesting things in Flutter, take a look at the following articles:

You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.


Related Articles

Latest Articles