Adding distinct to a flutter moor query

Issue

I have the following flutter moor query

(select(recipeGarnishes)..where((tbl) => tbl.postGarnish.equals(true))).get();

How would I add the distinct condition to the query?

Update:
The query I want to write is:

select DISTINCT garnishName from RecipeGarnishes where postGarnish = 'true'

garnishName and postGarnish are columns in my RecipeGarnishes table

Update 2:

Based on the answer, I tried this.

final query = selectOnly(recipeGarnishes, distinct: true)
                ..addColumns([recipeGarnishes.garnishName])
                ..where(recipeGarnishes.postGarnish.equals(postGarnish));
List<TypedResult> result = await query.get();

return result.map((row) => row.readTable(recipeGarnishes)).toList();

But it gives me the following error

Moor: Sent SELECT DISTINCT recipe_garnishes.garnish_name AS "recipe_garnishes.garnish_name" FROM recipe_garnishes WHERE recipe_garnishes.post_garnish = ?; with args [1]

[ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: NoSuchMethodError: The getter ‘garnishName’ was called on null.

Solution

The query itself is correct, but you can’t read the result like that: row.readTable would return a full row with all columns. However, you only select a single column (garnishName), so moor can’t load the row and returns null instead.

You can use

final query = selectOnly(recipeGarnishes, distinct: true)
                ..addColumns([recipeGarnishes.garnishName])
                ..where(recipeGarnishes.postGarnish.equals(postGarnish));

return query.map((row) => row.read(recipeGarnishes.garnishName)).get();

Answered By – simolus3

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.