searchCountries method

List<CountryModel> searchCountries(
  1. String query, {
  2. int limit = 50,
})

Implementation

List<CountryModel> searchCountries(String query, {int limit = 50}) {
  if (_countries == null || query.isEmpty) return [];

  final cacheKey = '${query.toLowerCase()}:$limit';

  // Check cache first - instant results for repeat searches
  if (_countrySearchCache.containsKey(cacheKey)) {
    return _countrySearchCache[cacheKey]!;
  }

  final lowerQuery = query.toLowerCase();
  final results = <CountryModel>[];
  final Set<String> addedIds = {};

  // Priority 1: Exact matches
  _countrySearchIndex?.forEach((prefix, countries) {
    if (prefix == lowerQuery && results.length < limit) {
      for (final country in countries) {
        if (!addedIds.contains(country.id) && results.length < limit) {
          results.add(country);
          addedIds.add(country.id);
        }
      }
    }
  });

  // Priority 2: Starts with query
  _countrySearchIndex?.forEach((prefix, countries) {
    if (prefix.startsWith(lowerQuery) && prefix != lowerQuery && results.length < limit) {
      for (final country in countries) {
        if (!addedIds.contains(country.id) && results.length < limit) {
          results.add(country);
          addedIds.add(country.id);
        }
      }
    }
  });

  // Priority 3: Contains query (fallback for edge cases)
  if (results.length < limit) {
    for (final country in _countries!) {
      if (results.length >= limit) break;
      if (!addedIds.contains(country.id) &&
          (country.name.toLowerCase().contains(lowerQuery) ||
           country.sortName.toLowerCase().contains(lowerQuery))) {
        results.add(country);
        addedIds.add(country.id);
      }
    }
  }

  // Cache results for super fast repeat access
  _manageCacheSize(_countrySearchCache, cacheKey, results);
  return results;
}