Flutter Tinder like app performance issues

42 Views Asked by At

Stack Overflow community!

I'm working on a feature for a mobile app where users can swipe through a list of items (let's say books for the sake of example), and the app will match these items based on a set of user preferences (e.g., preferred genres). Each item has its own list of characteristics (in this case, genres), and I need to compare these against the user's preferences to find matches.

The core of my current implementation in Dart looks something like this:

void checkForMatch() {
 if (preferredGenres != null) {
var preferredGenresKeys = HashSet<String>.from(
  preferredGenres!.map((genre) => genre.genreKey)
);

remainingBooks?.removeWhere((book) {
  bool allGenresMatch = true;
  for (var genreKey in book.genresForBook) {
    if (!preferredGenresKeys.contains(genreKey)) {
      allGenresMatch = false;
      break;
    }
  }

  if (allGenresMatch) {
    matchedBooksSet.add(book);
  }

  return allGenresMatch;
});

} }

This method is called every time a user swipes, but I'm encountering performance issues, especially when the list of items and preferences grow larger. The lag becomes noticeable, affecting the user experience.

Any insights, code snippets, or pointers to relevant resources would be greatly appreciated. Thank you in advance for your help!

1

There are 1 best solutions below

1
Bholendra Singh On

You can use checkForMatch() function like this.

void checkForMatch() {
      // Check if preferredGenres is not null
      if (preferredGenres != null) {
        // Create a set of genre keys from preferredGenres
        var preferredGenresKeys = HashSet<String>.from(
            preferredGenres!.map((genre) => genre.genreKey));
    
        // Initialize a list to store matched books
        List<Book> matchedBooks = [];
    
        // Iterate through remainingBooks
        for (var book in remainingBooks!) {
          // Assume all genres match initially
          bool allGenresMatch = true;
    
          // Check if all genres of the book are present in preferredGenresKeys
          for (var genreKey in book.genresForBook) {
            if (!preferredGenresKeys.contains(genreKey)) {
              // If a genre doesn't match, set allGenresMatch to false and break the loop
              allGenresMatch = false;
              break;
            }
          }
          
          // If all genres match, add the book to matchedBooks
          if (allGenresMatch) {
            matchedBooks.add(book);
          }
        }
        
        // Add all matched books to matchedBooksSet
        matchedBooksSet.addAll(matchedBooks);
        
        // Remove matched books from remainingBooks
        remainingBooks!.removeWhere((book) => matchedBooks.contains(book));
      }
    }