DEV Community

Flutter Tanzania
Flutter Tanzania

Posted on

Implementing Autocomplete in Your Flutter App: A Beginner's Guide

Introduction

Autocomplete is a common feature in modern apps that makes it easier for users to enter data by suggesting possible options as they type. Flutter has an Autocomplete widget that you can use to create an autocomplete feature in your app.

The Autocomplete widget is a user interface component in Flutter that helps users search and select values from a list of options. It's similar to the auto-suggest feature found in many search engines and other web applications.

The Autocomplete widget takes a list of options and a function that returns a list of options that match the user's input. It displays a TextField where the user can type in their search query. As the user types, the Autocomplete widget filters the options based on the input and displays them in a dropdown menu. The user can then select one of the options from the menu, and the selected value is returned to the app.

The Autocomplete widget is highly customizable and can be used to implement a variety of search and selection use cases. For example, it can be used to search for a user by name, select a location from a list of cities, or pick a color from a list of options.

To use the Autocomplete widget in your Flutter app, you need to provide a list of options, a function that returns the options that match the user's input, and a callback function that is called when the user selects an option.

In this tutorial, we'll walk through how to use the Autocomplete widget in Flutter to create an autocomplete feature for a list of countries. In this app we will build a simple app but it will be help full.

Getting Started

Before we dive into the code, make sure you have Flutter installed and set up on your machine. If you need help with this, you can refer to the official Flutter documentation.

Creating the Project

To get started, open your IDE and create a new Flutter project. We'll name our project autocomplete_demo.

Creating the Data

In this example, we'll be using a list of countries as our data source. To keep things simple, we'll use a static list of countries, but in a real-world scenario, you'd likely be getting the data from an API.

First, create a new file called countries.dart in the lib directory of your project. In this file, create a list of countries:

List<String> countries = [
  'Afghanistan',
  'Albania',
  'Algeria',
  'Andorra',
  'Angola',
  'Antigua and Barbuda',
  'Argentina',
  'Armenia',
  'Australia',
  'Austria',
  'Azerbaijan',
  'Bahamas',
  'Bahrain',
  'Bangladesh',
  'Barbados',
  'Belarus',
  'Belgium',
  'Belize',
  'Benin',
  'Bhutan',
  'Bolivia',
  'Bosnia and Herzegovina',
  'Botswana',
  'Brazil',
  'Brunei',
  'Bulgaria',
  'Burkina Faso',
  'Burundi',
  'Cabo Verde',
  'Cambodia',
  'Cameroon',
  'Canada',
  'Central African Republic',
  'Chad',
  'Chile',
  'China',
  'Colombia',
  'Comoros',
  'Congo, Democratic Republic of the',
  'Congo, Republic of the',
  'Costa Rica',
  'Cote d\'Ivoire',
  'Croatia',
  'Cuba',
  'Cyprus',
  'Czech Republic',
  'Denmark',
  'Djibouti',
  'Dominica',
  'Dominican Republic',
  'Ecuador',
  'Egypt',
  'El Salvador',
  'Equatorial Guinea',
  'Eritrea',
  'Estonia',
  'Eswatini',
  'Ethiopia',
  'Fiji',
  'Finland',
  'France',
  'Gabon',
  'Gambia',
  'Georgia',
  'Germany',
  'Ghana',
  'Greece',
  'Grenada',
  'Guatemala',
  'Guinea',
  'Guinea-Bissau',
  'Guyana',
  'Haiti',
  'Honduras',
  'Hungary',
  'Iceland',
  'India',
  'Indonesia',
  'Iran',
  'Iraq',
  'Ireland',
  'Israel',
  'Italy',
  'Jamaica',
'Japan',
'Jordan',
'Kazakhstan',
'Kenya',
'Kiribati',
'Kosovo',
'Kuwait',
'Kyrgyzstan',
'Laos',
'Latvia',
'Lebanon',
'Lesotho',
'Liberia',
'Libya',
'Liechtenstein',
'Lithuania',
'Luxembourg',
'Madagascar',
'Malawi',
'Malaysia',
'Maldives',
'Mali',
'Malta',
'Marshall Islands',
'Mauritania',
'Mauritius',
'Mexico',
'Micronesia',
'Moldova',
'Monaco',
'Mongolia',
'Montenegro',
'Morocco',
'Mozambique',
'Myanmar',
'Namibia',
'Nauru',
'Nepal',
'Netherlands',
'New Zealand',
'Nicaragua',
'Niger',
'Nigeria',
'North Korea',
'North Macedonia',
'Norway',
'Oman',
'Pakistan',
'Palau',
'Palestine',
'Panama',
'Papua New Guinea',
'Paraguay',
'Peru',
'Philippines',
'Poland',
'Portugal',
'Qatar',
'Romania',
'Russia',
'Rwanda',
'Saint Kitts and Nevis',
'Saint Lucia',
'Saint Vincent and the Grenadines',
'Samoa',
'San Marino',
'Sao Tome and Principe',
'Saudi Arabia',
'Senegal',
'Serbia',
'Seychelles',
'Sierra Leone',
'Singapore',
'Slovakia',
'Slovenia',
'Solomon Islands',
'Somalia',
'South Africa',
'South Korea',
'South Sudan',
'Spain',
'Sri Lanka',
'Sudan',
'Suriname',
'Sweden',
'Switzerland',
'Syria',
'Taiwan',
'Tajikistan',
'Tanzania',
'Thailand',
'Timor-Leste',
'Togo',
'Tonga',
'Trinidad and Tobago',
'Tunisia',
'Turkey',
'Turkmenistan',
'Tuvalu',
'Uganda',
'Ukraine',
'United Arab Emirates',
'United Kingdom',
'United States of America',
'Uruguay',
'Uzbekistan',
'Vanuatu',
'Vatican City',
'Venezuela',
'Vietnam',
'Yemen',
'Zambia',
'Zimbabwe',
];
Enter fullscreen mode Exit fullscreen mode

Creating the Autocomplete Widget

Next, create a new file called autocomplete_demo.dart in the lib directory of your project. In this file, we'll create a stateful widget called AutocompleteDemo that will display the Autocomplete widget.

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

class AutocompleteDemo extends StatefulWidget {
  const AutocompleteDemo({super.key});

  @override
  _AutocompleteDemoState createState() => _AutocompleteDemoState();
}

class _AutocompleteDemoState extends State<AutocompleteDemo> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Autocomplete Demo'),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Autocomplete<String>(
            optionsBuilder: (TextEditingValue textEditingValue) {
              if (textEditingValue.text == '') {
                return const Iterable<String>.empty();
              }
              return countries.where((country) => country
                  .toLowerCase()
                  .contains(textEditingValue.text.toLowerCase()));
            },
            onSelected: (String selection) {
              print('You selected $selection');
            },
          ),
        ),
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Here, we're creating an Autocomplete widget and passing in two parameters: optionsBuilder and onSelected.

The optionsBuilder parameter takes a function that takes a TextEditingValue and returns an iterable of options. In our case, we check if the search query is empty and return an empty iterable if it is. Otherwise, we return a filtered list of countries based on the search query.

The onSelected parameter takes a function that is called when an option is selected from the dropdown. In our case, we simply print the selected country to the console.

Adding the Autocomplete Widget to the App

To add the Autocomplete widget to our app, we need to update the MyApp widget in main.dart to navigate to our AutocompleteDemo widget when the app is launched.

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

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Autocomplete Demo',
      home: AutocompleteDemo(),
    );
  }
}

Enter fullscreen mode Exit fullscreen mode

Running the App

Now that we've created the Autocomplete widget and added it to our app, we can run the app and see it in action. To do this, simply run the app by clicking the "Run" button in your IDE or by running the following command in your terminal:

flutter run

When the app is launched, you should see a search bar at the center of the screen. Try typing a few letters of a country name and see the dropdown list of matching countries appear. When you select a country, its name should be printed to the console.

Congratulations! You've created an Autocomplete widget in Flutter. This widget can be used in a variety of situations where users need to search through a large list of items, making it a valuable tool for any Flutter developer.

You can view it's full code in our GitHub repo here

Top comments (0)