DEV Community

Cover image for Flutter Web and Search
aseem wangoo
aseem wangoo

Posted on

Flutter Web and Search

In case it helped :)
Pass Me A Coffee!!

Website: https://web.flatteredwithflutter.com/#/

We will cover briefly about

  1. Implement Search in Flutter Web
  2. Saving the user searches (Bonus)
  3. Displaying user search history (Bonus)

Article here: https://flatteredwithflutter.com/how-to-implement-search-in-flutter-web

1. Implement Search in Flutter Web

Let’s start with the algorithm

We extracted out the algorithm(StringSearch) for searching and put inside a separate file called string_search.dart

StringSearch(this.input, this.searchTerm)
  • input: List<String>, e.g [‘Hey’, ‘there’]
  • searchTerm: String which the user searched. e.g here

Condition: Length of searchTerm should be more than 1 letter. e.g If user searches for h, we return empty.

To get the relevant results, we have a method called

List<String> relevantResults() {
  if (searchTerm.length < 2) {
      return [];
  }
  return input
        .where((item) => item.toLowerCase().contains(searchTerm.toLowerCase()))
        .toList();
}

We check if the search term is present inside the list of inputs. (Linear Search)

The matches found are returned as a list.

Flutter Web and Search

Integrate with UI

Our search bar (a custom widget) exposes a property called onChange. 

Theoretically, when a user starts typing, it should get the relevant results.

  • But for making this more human-like, we listen to user input after every 300 milliseconds.
  • Introduce debouncer, (a custom class)
Flutter Web and Search — Debouncer

This fires a timer (after 300 milliseconds).

  • We include debouncer within the onChange property
final _debouncer = Debouncer();

// INTERNAL IMPLEMENTATION

onChanged: (val) {
  _debouncer.call(() {
     if (widget.onChanged != null) widget.onChanged(val);
  });
},

Flutter Web and Search

Displaying Search Results

We create a class SearchCommand which is

class SearchCommand extends GenericNotifier {
   List<String> showSearchResults(String searchTerm) {
      _searchedResults = StringSearch(_articles,searchTerm).relevantResults();
       notify();
       return _searchedResults;
   }
}
class GenericNotifier extends ChangeNotifier {
  void notify() => notifyListeners();
}

This search command class is basically a change notifier. It has a method called showSearchResults, 

  • which takes in the user typed search term
  • searches using StringSearch (described above)

Note: Input to StringSearch is the list of articles (predefined inside our app)

  • returns the relevant results and calls notify

Now, for showing these results, we need an overlay. Luckily, the Flutter framework has an Overlay widget to create widgets that float on top of everything else, without having to restructure your whole view.

Interesting article on overlays

  • We create an overlay entry
Flutter Web and Search — Overlay Entry

We simply render the results from our SearchCommand class, as a ListTile

Note: If our search bar is in focus, we need to display the above overlay entry and remove, when the bar is unfocused.

  • Attach a focus node to our search bar
RoundedShape(
   textController: controller,
   focusNode: focusNode,
   onChanged: (term) => searchCommand.showSearchResults(term),
)

and for showing/hiding the overlay entry, we simply check

OverlayEntry overlayEntry;
// inside initState
if (focusNode.hasFocus) {
   overlayEntry = createOverlayEntry();
   Overlay.of(context).insert(overlayEntry);
} else {
   overlayEntry?.remove();
}

Problem

The overlay entry does not move as we scroll our web page.

Flutter provides us CompositedTransformFollower andCompositedTransformTarget for exactly our use case.

followerwill follow the target wherever it goes.

  • Wrap overlay entry with CompositedTransformFollower
  • Wrap the search bar with CompositedTransformTarget

This makes sure if we scroll our webpage, then the overlay results follow the search bar widget.

Interesting article on CompositeTransform

2. Saving the user searches

We want to save the user search terms and display them later for step 3.

For saving the search terms, we will use Hive in Flutter Web.

Once the user clicks on the search result, we insert the entry inside the Hive. We have a class SearchResultCommand, which exposes the tap method

class SearchResultCommand {
   void tap(String result, String searchTerm) {
     var article =
      _combinedInputList.where((item) =>     item.articleName==result).first;
     // INSERT IN CACHE
     _insertInCache(article, searchTerm);
     _navTo(article.articleRoute);
   }
}
  • result: is the clicked search result, e.g Hooks
  • searchTerm: the user searched term, e.g ook

Details regarding the result are searched against the existing articles list and then inserted (ArticleModel) into the cache along with the search term (ook)

  • For inserting the data into the cache, we create a new model called CachedSearches 

  • For inserting this data into the cache, we use Hive.

Logic: If the item exists in cache, increase the occurence of that item, if not then insert.

  • Let’s get the opened box using
final _searchBox = Hive.box<CachedSearches>('searches');
  • For checking the item in the cache,

Note: If the item is not present, then hive returns null.

bool checkIfExistsInCache(CachedSearches data) {
  final val = _searchBox.get(data.phrase);
  if (val == null) {
     return false;
  }
  return true;
}
  • For data insertion,
_searchBox.put('key', 'value') ---> GENERIC
_searchBox.put(data.phrase, data)---> OUR CASE SPECIFIC

Final result,


Flutter Web and Search — Hive

3. Displaying user search history

For displaying search history, we use our custom paginated data table.

Hive exposes listeners for the Hive Boxes. We utilize this listener on the box to show updates instantly.

final _searchBox = Hive.box<CachedSearches>('searches');
// FROM ABOVE
Box<CachedSearches> get cacheSearchBox => _searchBox;
cacheSearchBox.listenable() ----> LISTENABLE exposed BY HIVE

Note: listenable is present inside hive_flutter

We can wrap this listenable inside ValueListenableBuilder

Flutter Web and Search

Each time any changes are made to the box’s entries, it gets notified to us.

  • For removing an item from the cache,
final _searchBox = Hive.box<CachedSearches>('searches');
// FROM ABOVE

Future<void> clearItemInCache(CachedSearches data) async {
   await _searchBox.delete(data.phrase);
}

This deletes the particular phrase from the cache.

  • For removing the entire history from the cache,
_searchBox.clear()

This removes all the entries from the cache.

In case it helped :)
Pass Me A Coffee!!

Hosted URL : https://web.flatteredwithflutter.com/#/

Source code for Flutter Web App..

Top comments (0)