Search code examples
databasesqliteflutterfloor

Flutter floor database Future bool action in DAO file?


While using floor database can we set an action which will turn as a boolean like below example?

Future<bool> isItAdded(in user_id) async{
    var = dbClient = await db;
    List<Map> list = await dbClient.rawQuery{SELECT * FROM Users WHERE user_id}, [user_id]}
    return list.lenght > 0 ? true : false
}

Solution

  • You may write DAO object:

    @dao
    abstract class UsersDao {
      @Query('SELECT * FROM users WHERE user_id = :userId')
      Future<List<User>> findUsers(Int userId);
    }
    

    Before that you neeed to create entity:

    @Entity(tableName: 'users')
    class User{
      @PrimaryKey(autoGenerate: true)
      final int id;
    
      @ColumnInfo(name: 'user_id')
      final int userId;
    }
    

    Also you need to create database access object:

    part 'database.g.dart'; // the generated code will be there
    
     @Database(version: 1, entities: [User])
     abstract class AppDatabase extends FloorDatabase {
       UsersDao get usersDao;
     }
    

    Then generate additional code by command:

    flutter packages pub run build_runner build
    

    And then write check function inside database access object:

    Future<bool> isItAdded(in user_id) async {
        List<User> list = await usersDao.findUsers(user_id);
        return list.lenght > 0;
    }
    

    The best solution is not to add user_id column and use only unique id column.