Drift/Moor/Flutter StateError (Bad state: No element) when selecting single row with getSingle()

414 Views Asked by At

When retrieving data from a Drift database using the .getSingle() method, if there is no row matching the search criterion, a StateError (Bad state: No element) error is thrown. Is this expected behavior?

  Future<MyData> singleMyData(String id) {
    return (select(myDatas)..where((t) => t.id.equals(id)))
        .getSingle();
  }

...

var singleData = await myDatabase.singleMyData("theId");
1

There are 1 best solutions below

0
Mia loha.dev On

It means that the element is not in the database. Try this instead:

// can return empty list
  Future<List<DATA>> lookForSong(String songId) {
    return (select(records)..where((tbl) => tbl.uid.equals(recordId))).get();
  }

// data is sure to be present
  Future<DATA> getSong(String songId) {
    return (select(records)..where((tbl) => tbl.uid.equals(recordId))).getSingle();
  }