I'm trying to develop a simple app with user signup and login. Whenever I'm attempting a log in with a non existent username in the database, I'd like to display the message "no such user" or something similar. I'm trying to handle the Bad State: no Element exception, but the exception doesn't seem to be "catch-able".
At first my code was:
Future<Users> fetchByUsername(String nomeUtente) async {
final database = await DatabaseService("users.db").database;
final users = await database.rawQuery('''SELECT * from $tableName WHERE nomeUtente = ?''', [nomeUtente]);
return Users.fromSqfliteDatabase(users.first);
}
Then I changed it to be:
Future<Users?> fetchByUsername(String nomeUtente) async {
final database = await DatabaseService("users.db").database;
try {
final users = await database.rawQuery('''SELECT * from $tableName WHERE nomeUtente = ?''', [nomeUtente]);
return Users.fromSqfliteDatabase(users.first);
} on Exception catch (e) {
return null;
}
}
But nothing happens, and in general the IDE itself discourages the use of the "Exception" keyword as it is. I'd like to return a fake user or just null whenever the user isn't found.
EDIT: I'm currently working around it by using a fetchAll function and running a for loop to check whether the user exists or not. For loops can be troublesome, so I'd like to resolve it by select query.
This is my Users class!
class Users {
final String nomeUtente;
final String email;
final String password;
final String dataNascita;
Users({
required this.nomeUtente,
required this.email,
required this.password,
required this.dataNascita,
});
factory Users.fromSqfliteDatabase(Map<String, dynamic> map) => Users (
nomeUtente: map['nomeUtente']?.toString() ?? '',
email: map['email']?.toString() ?? '',
password: map['password']?.toString() ?? '',
dataNascita: map['dataNascita']?.toString() ?? '',
);
}
Have you tried using catch without the caveat of an Exception?
Future<Users?> fetchByUsername(String nomeUtente) async {
final database = await DatabaseService("users.db").database;
try {
final users = await database.rawQuery('''SELECT * from $tableName WHERE nomeUtente = ?''', [nomeUtente]);
return Users.fromSqfliteDatabase(users.first);
} catch (e) {
return null;
}
}