Flutter Autocomplete example

Last updated on January 13, 2022 A Goodman Loading... 3 comments

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.

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);

  @override
  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);

  @override
  _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 = [
    'Alligator',
    'Buffalo',
    'Chicken',
    'Dog',
    'Eagle',
    'Frog'
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Kindacode.com'),
      ),
      body: Column(
        children: [
          Autocomplete<String>(
            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) =>
                  suggestion.toLowerCase().contains(value.text.toLowerCase()));
            },
            onSelected: (value) {
              setState(() {
                _selectedAnimal = value;
              });
            },
          ),
          const SizedBox(
            height: 30,
          ),
          Text(_selectedAnimal ?? 'Type something (a, b, c, etc)'),
        ],
      ),
    );
  }
}

Conclusion

This 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.

Subscribe
Notify of
guest
3 Comments
Inline Feedbacks
View all comments
Daniyal Dolare
Daniyal Dolare
6 months ago

Thanks a lot!

Andrew King
Andrew King
8 months ago

Thanks for the post.Have you got any thoughts on the best way to use an API/Future in optionsBuilder

محمدحسین فخرآوری
محمدحسین فخرآوری
9 months ago

hi
good post filter

Related Articles