how to do suggestionCallback in typeahead flutter?

1,779

The example service is here, pattern in CitiesService example means contain some characters

https://github.com/AbdulRahmanAlHamali/flutter_typeahead/blob/master/example/lib/data.dart

import 'dart:math';

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 List<String> cities = [
    'Beirut',
    'Damascus',
    'San Fransisco',
    'Rome',
    'Los Angeles',
    'Madrid',
    'Bali',
    'Barcelona',
    'Paris',
    'Bucharest',
    'New York City',
    'Philadelphia',
    'Sydney',
  ];

  static List<String> getSuggestions(String query) {
    List<String> matches = List();
    matches.addAll(cities);

    matches.retainWhere((s) => s.toLowerCase().contains(query.toLowerCase()));
    return matches;
  }
}
Share:
1,779
santosh adhikari
Author by

santosh adhikari

Updated on December 01, 2022

Comments

  • santosh adhikari
    santosh adhikari over 1 year

    i'm beginner in flutter, in my flutter project i used flutter_typeahead package but i did not able to execute this code.

    i did not get proper guidance from this documentation https://pub.dev/documentation/flutter_typeahead/latest/flutter_typeahead/flutter_typeahead-library.html

        suggestionsCallback: (pattern) {
          return CitiesService.getSuggestions(pattern);
         }
    
  • chunhunghan
    chunhunghan over 4 years
    if it solve your problem. please mark this as answer. if not solve your problem please tell me further error message. thanks.
  • omega_prime
    omega_prime almost 4 years
    brilliant answer! Now I need to figure out how to use an API with it :(