flutter_typeahead 0.4.1

  • README.md
  • CHANGELOG.md
  • Example
  • Installing
  • Versions
  • 95

Flutter TypeAhead

A TypeAhead (autocomplete) widget for Flutter, where you can show suggestions to users as they type

Features

  • Shows suggestions in an overlay that floats on top of other widgets
  • Allows you to specify what the suggestions will look like through a builder function
  • Allows you to specify what happens when the user taps a suggestion
  • Accepts all the parameters that traditional TextFields accept, like decoration, custom TextEditingController, text styling, etc.
  • Provides two versions, a normal version and a FormField version that accepts validation, submitting, etc.
  • Provides high customizability; you can customize the suggestion box decoration, the loading bar, the animation, the debounce duration, etc.

Installation

See the installation instructions on pub.

Usage examples

You can import the package with:

import 'package:flutter_typeahead/flutter_typeahead.dart';

and then use it as follows:

Example 1:

TypeAheadField(
  textFieldConfiguration: TextFieldConfiguration(
    autofocus: true,
    style: DefaultTextStyle.of(context).style.copyWith(
      fontStyle: FontStyle.italic
    ),
    decoration: InputDecoration(
      border: OutlineInputBorder()
    )
  ),
  suggestionsCallback: (pattern) async {
    return await BackendService.getSuggestions(pattern);
  },
  itemBuilder: (context, suggestion) {
    return ListTile(
      leading: Icon(Icons.shopping_cart),
      title: Text(suggestion['name']),
      subtitle: Text('\$${suggestion['price']}'),
    );
  },
  onSuggestionSelected: (suggestion) {
    Navigator.of(context).push(MaterialPageRoute(
      builder: (context) => ProductPage(product: suggestion)
    ));
  },
)

In the code above, the textFieldConfiguration property allows us to configure the displayed TextField as we want. In this example, we are configuring the autofocus, style and decoration properties.

The suggestionsCallback is called with the search string that the user types, and is expected to return a List of data either synchronously or asynchronously. In this example, we are calling an asynchronous function called BackendService.getSuggestions which fetches the list of suggestions.

The itemBuilder is called to build a widget for each suggestion. In this example, we build a simple ListTile that shows the name and the price of the item. Please note that you shouldn't provide an onTap callback here. The TypeAhead widget takes care of that.

The onSuggestionSelected is a callback called when the user taps a suggestion. In this example, when the user taps a suggestion, we navigate to a page that shows us the information of the tapped product.

Example 2:

Here's another example, where we use the TypeAheadFormField inside a Form:

final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
final TextEditingController _typeAheadController = TextEditingController();
String _selectedCity;
...
Form(
  key: this._formKey,
  child: Padding(
    padding: EdgeInsets.all(32.0),
    child: Column(
      children: <Widget>[
        Text(
          'What is your favorite city?'
        ),
        TypeAheadFormField(
          textFieldConfiguration: TextFieldConfiguration(
            controller: this._typeAheadController,
            decoration: InputDecoration(
              labelText: 'City'
            )
          ),          
          suggestionsCallback: (pattern) {
            return CitiesService.getSuggestions(pattern);
          },
          itemBuilder: (context, suggestion) {
            return ListTile(
              title: Text(suggestion),
            );
          },
          transitionBuilder: (context, suggestionsBox, controller) {
            return suggestionsBox;
          },
          onSuggestionSelected: (suggestion) {
            this._typeAheadController.text = suggestion;
          },
          validator: (value) {
            if (value.isEmpty) {
              return 'Please select a city';
            }
          },
          onSaved: (value) => this._selectedCity = value,
        ),
        SizedBox(height: 10.0,),
        RaisedButton(
          child: Text('Submit'),
          onPressed: () {
            if (this._formKey.currentState.validate()) {
              this._formKey.currentState.save();
              Scaffold.of(context).showSnackBar(SnackBar(
                content: Text('Your Favorite City is ${this._selectedCity}')
              ));
            }
          },
        )
      ],
    ),
  ),
)

Here, we assign to the controller property of the textFieldConfiguration a TextEditingController that we call _typeAheadController. We use this controller in the onSuggestionSelected callback to set the value of the TextField to the selected suggestion.

The validator callback can be used like any FormField.validator function. In our example, it checks whether a value has been entered, and displays an error message if not. The onSaved callback is used to save the value of the field to the _selectedCity member variable.

The transitionBuilder allows us to customize the animation of the suggestion box. In this example, we are returning the suggestionsBox immediately, meaning that we don't want any animation.

Customizations

TypeAhead widgets consist of a TextField and a suggestion box that shows as the user types. Both are highly customizable

Customizing the TextField

You can customize the text field using the textFieldConfiguration property. You provide this property with an instance of TextFieldConfiguration, which allows you to configure all the usual properties of TextField, like decoration, style, controller, focusNode, autofocus, enabled, etc.

Customizing the Suggestions Box

TypeAhead provides default configurations for the suggestions box. You can, however, override most of them.

Customizing the loader, the error and the "no items found" message

You can use the loadingBuilder, errorBuilder and noItemsFoundBuilder to customize their corresponding widgets. For example, to show a custom error widget:

errorBuilder: (BuildContext context, Object error) =>
  Text(
    '$error',
    style: TextStyle(
      color: Theme.of(context).errorColor
    )
  )

Customizing the animation

You can customize the suggestion box animation through 3 parameters: the animationDuration, the animationStart, and the transitionBuilder.

The animationDuration specifies how long the animation should take, while the animationStart specified what point (between 0.0 and 1.0) the animation should start from. The transitionBuilder accepts the suggestionsBox and animationController as parameters, and should return a widget that uses the animationController to animate the display of the suggestionsBox. For example:

transitionBuilder: (context, suggestionsBox, animationController) =>
  FadeTransition(
    child: suggestionsBox,
    opacity: CurvedAnimation(
      parent: animationController,
      curve: Curves.fastOutSlowIn
    ),
  )

This uses FadeTransition to fade the suggestionsBox into the view. Note how the animationController was provided as the parent of the animation.

In order to fully remove the animation, transitionBuilder should simply return the suggestionsBox. This callback could also be used to wrap the suggestionsBox with any desired widgets, not necessarily for animation.

Customizing the debounce duration

The suggestions box does not fire for each character the user types. Instead, we wait until the user is idle for a duration of time, and then call the suggestionsCallback. The duration defaults to 300 milliseconds, but can be configured using the debounceDuration parameter.

Customizing the offset of the suggestions box

By default, the suggestions box is displayed 5 pixels below the TextField. You can change this by changing the suggestionsBoxVerticalOffset property.

Customizing the decoration of the suggestions box

You can also customize the decoration of the suggestions box using the suggestionsBoxDecoration property. For example, to remove the elevation of the suggestions box, you can write:

suggestionsBoxDecoration: SuggestionsBoxDecoration(
  elevation: 0.0
)

For more information

Visit the API Documentation

How you can help

  • You can report any issues you find
  • You can suggest any missing features that could be useful to have
  • You can submit pull requests
  • You can share the package on social media, to let more people know about it: https://pub.dartlang.org/packages/flutter_typeahead

0.1.0 - 31/08/2018

  • Initial Release.

0.1.1 - 31/08/2018

  • Fixed CHANGELOG.
  • Small fix to documentation

0.1.2 - 31/08/2018

  • Small fix to README

0.2.0 - 02/09/2018

  • Changed the suggestions box decoration to decorate a material sheet instead of decorating a container
  • Moved the TextField properties inside a class called TextFieldConfiguration, which is provided to the TypeAhead widgets through a textFieldConfiguration property. This was done to decrease the clutter in the interface
  • Added more configuration properties to the TextField
  • Added a configurable vertical offset for the suggestions box
  • Changed the mechanism used to open/close the suggestions box
  • Added meta-tags to README for SEO
  • Updated the GIF to show the changes
  • Added "How you can help" section to README

0.2.1 - 04/09/2018

  • Added mention of 'autocomplete' in README and pubspec
  • Executed 'flutter format'

0.3.0 - 15/09/2018

  • Added a constraints property to the SuggestionsBoxDecorations which allows to set the height and width of the suggestions box

0.4.0 - 20/09/2018

  • Added property getImmediateSuggestions to allow fetching suggestions before the user types
  • Added assertion in the form field to disallow having initialValue and textFieldConfiguration.controller defined at the same time

0.4.1 - 20/09/2018

  • Added property getImmediateSuggestions to the form field implementation

example/lib/main.dart

import 'dart:async';
import 'dart:math';

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(
      title: 'flutter_typeahead demo',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  
  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 2,
      child: Scaffold(
        appBar: AppBar(
          title: TabBar(
              tabs: [
                Tab(
                  text: 'Example 1: Navigation',
                ),
                Tab(
                    text: 'Example 2: Form'
                )
              ]
          ),
        ),
        body: TabBarView(
          children: [
            NavigationExample(),
            FormExample()
          ]
        )
      ),
    );
  }
}

class NavigationExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(32.0),
      child: Column(
        children: <Widget>[
          SizedBox(height: 10.0,),
          TypeAheadField(
            textFieldConfiguration: TextFieldConfiguration(
              autofocus: true,
              style: DefaultTextStyle.of(context).style.copyWith(
                  fontStyle: FontStyle.italic
              ),
              decoration: InputDecoration(
                border: OutlineInputBorder(),
                hintText: 'What are you looking for?'
              ),
            ),
            suggestionsCallback: (pattern) async {
              return await BackendService.getSuggestions(pattern);
            },
            itemBuilder: (context, suggestion) {
              return ListTile(
                leading: Icon(Icons.shopping_cart),
                title: Text(suggestion['name']),
                subtitle: Text('\$${suggestion['price']}'),
              );
            },
            onSuggestionSelected: (suggestion) {
              Navigator.of(context).push(MaterialPageRoute(
                builder: (context) => ProductPage(product: suggestion)
              ));
            },
          ),
        ],
      ),
    );
  }
}

class FormExample extends StatefulWidget {
  @override
  _FormExampleState createState() => _FormExampleState();
}

class _FormExampleState extends State<FormExample> {

  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final TextEditingController _typeAheadController = TextEditingController();

  String _selectedCity;

  @override
  Widget build(BuildContext context) {
    return Form(
      key: this._formKey,
      child: Padding(
        padding: EdgeInsets.all(32.0),
        child: Column(
          children: <Widget>[
            Text(
              'What is your favorite city?'
            ),
            TypeAheadFormField(
              textFieldConfiguration: TextFieldConfiguration(
                decoration: InputDecoration(
                    labelText: 'City'
                ),
                controller: this._typeAheadController,
              ),
              suggestionsCallback: (pattern) {
                return CitiesService.getSuggestions(pattern);
              },
              itemBuilder: (context, suggestion) {
                return ListTile(
                  title: Text(suggestion),
                );
              },
              transitionBuilder: (context, suggestionsBox, controller) {
                return suggestionsBox;
              },
              onSuggestionSelected: (suggestion) {
                this._typeAheadController.text = suggestion;
              },
              validator: (value) {
                if (value.isEmpty) {
                  return 'Please select a city';
                }
              },
              onSaved: (value) => this._selectedCity = value,
            ),
            SizedBox(height: 10.0,),
            RaisedButton(
              child: Text('Submit'),
              onPressed: () {
                if (this._formKey.currentState.validate()) {
                  this._formKey.currentState.save();
                  Scaffold.of(context).showSnackBar(SnackBar(
                    content: Text('Your Favorite City is ${this._selectedCity}')
                  ));
                }
              },
            )
          ],
        ),
      ),
    );
  }
}


class ProductPage extends StatelessWidget {

  final Map<String, dynamic> product;

  ProductPage({this.product});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(50.0),
        child: Column(
          children: [
            Text(
              this.product['name'],
              style: Theme.of(context).textTheme.headline,
            ),
            Text(
              this.product['price'].toString() + ' USD',
              style: Theme.of(context).textTheme.subhead,
            )
          ],
        ),
      ),
    );
  }
}


class BackendService {
  static Future<List> getSuggestions(String query) async {
    await Future.delayed(Duration(seconds: 1));

    return List.generate(3, (index) {
      return {
        'name': query + index.toString(),
        'price': Random().nextInt(100)
      };
    });
  }
}

class CitiesService {

  static final cities = [
    'Beirut',
    'Damascus',
    'San Fransisco',
    'Rome',
    'Los Angeles',
    'Madrid',
    'Bali',
    'Barcelona',
    'Paris',
    'Bucharest'
  ];

  static getSuggestions(String query) {
    final cities = CitiesService.cities;

    cities.sort((a, b) {
      return CitiesService._distance(query, a) - CitiesService._distance(query, b);
    });

    return cities.take(4).toList();
  }

  // source: https://github.com/kseo/edit_distance/blob/master/lib/src/levenshtein.dart
  static int _distance(String s1, String s2) {
    if (s1 == s2) {
      return 0;
    }

    if (s1.length == 0) {
      return s2.length;
    }

    if (s2.length == 0) {
      return s1.length;
    }

    List<int> v0 = new List<int>(s2.length + 1);
    List<int> v1 = new List<int>(s2.length + 1);
    List<int> vtemp;

    for (var i = 0; i < v0.length; i++) {
      v0[i] = i;
    }

    for (var i = 0; i < s1.length; i++) {
      v1[0] = i + 1;

      for (var j = 0; j < s2.length; j++) {
        int cost = 1;
        if (s1.codeUnitAt(i) == s2.codeUnitAt(j)) {
          cost = 0;
        }
        v1[j + 1] = min(v1[j] + 1, min(v0[j + 1] + 1, v0[j] + cost));
      }

      vtemp = v0;
      v0 = v1;
      v1 = vtemp;
    }

    return v0[s2.length];
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  flutter_typeahead: ^0.4.1

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter packages get

Alternatively, your editor might support flutter packages get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:flutter_typeahead/flutter_typeahead.dart';
  
Version Uploaded Documentation Archive
0.4.1 Sep 20, 2018 Go to the documentation of flutter_typeahead 0.4.1 Download flutter_typeahead 0.4.1 archive
0.4.0 Sep 20, 2018 Go to the documentation of flutter_typeahead 0.4.0 Download flutter_typeahead 0.4.0 archive
0.3.0 Sep 15, 2018 Go to the documentation of flutter_typeahead 0.3.0 Download flutter_typeahead 0.3.0 archive
0.2.1 Sep 4, 2018 Go to the documentation of flutter_typeahead 0.2.1 Download flutter_typeahead 0.2.1 archive
0.2.0 Sep 2, 2018 Go to the documentation of flutter_typeahead 0.2.0 Download flutter_typeahead 0.2.0 archive
0.1.2 Aug 30, 2018 Go to the documentation of flutter_typeahead 0.1.2 Download flutter_typeahead 0.1.2 archive
0.1.1 Aug 30, 2018 Go to the documentation of flutter_typeahead 0.1.1 Download flutter_typeahead 0.1.1 archive
0.1.0 Aug 30, 2018 Go to the documentation of flutter_typeahead 0.1.0 Download flutter_typeahead 0.1.0 archive
Popularity:
Describes how popular the package is relative to other packages. [more]
89
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
95
Learn more about scoring.

We analyzed this package on Nov 14, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.0.0
  • pana: 0.12.6
  • Flutter: 0.11.3

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=1.19.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.11
meta 1.1.6
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test