How to write customSelect query using Flutter moor/drift

2.9k Views Asked by At

I'm stuck with this custom query with variable using moor. No list is returned when using SELECT * FROM books WHERE title LIKE searchString;. Am I missing something?

code:

Stream<List<Book>> getFilteredBook(String searchString) {
    searchString = 'the';
    return customSelect(
      //query works fine
      //'SELECT * FROM books;',
      'SELECT * FROM books WHERE title LIKE searchString;',
      variables: [
        Variable.withString(searchString),
      ],
      readsFrom: {books},
    ).watch().map((rows) {
      // Turning the data of a row into a Book object
      return rows.map((row) => Book.fromData(row.data)).toList();
    });
  }
1

There are 1 best solutions below

2
Hossein Yousefi On

You can use a question mark (?) as a placeholder for your variable:

  Stream<List<Book>> getFilteredBook(String searchString) {
    searchString = 'the';
    return customSelect(
      //query works fine
      //'SELECT * FROM books;',
      'SELECT * FROM books WHERE title LIKE ?;',
      variables: [
        Variable.withString(searchString),
      ],
      readsFrom: {books},
    ).watch().map((rows) {
      // Turning the data of a row into a Book object
      return rows.map((row) => Book.fromData(row.data)).toList();
    });
  }