I am getting a bit confused with Futures and nulls here. I have a table in sqflite called organisations, and I am trying to read from it a organisation by id. If not found return null, otherwise return a Organisation object.
import 'database_helper.dart';
import 'package:sqflite/sqflite.dart';
class Organisation {
late int organisationId;
late String name;
Organisation(
{
required this.organisationId,
required this.name,
});
Organisation.fromJson(Map<String, dynamic> json) {
organisationId = json["organisationId"]!;
name = json["name"];
}
Map<String, dynamic> toMap() {
return {
'organisation' : organisationId,
'name': name,
};
}
}
Future<Organisation?> readOrganisationById(int orgId) async {
final dbHelper = DatabaseHelper();
final db = await dbHelper.database;
final List<Map<String, dynamic>> maps = await db.rawQuery(
"SELECT * FROM organisations WHERE id = ?", [orgId]);
if (maps.isEmpty) {
return null;
} else {
return Organisation(
organisationId: maps[0]['organisationId'],
name: maps[0]['name']
);
}
}
I am then trying to call this like this, but the code editor is telling me : The getter 'name' isn't defined for the type 'Future<Organisation?>
Future<Organisation?> org = readOrganisationById(organisationId);
if (org != null) {
organisationName = org.name;
}
How should I call readOrganisationById and check for null?
In your code, you are doing:
Future<Organisation?> org = readOrganisationById(organisationId);
However, the above is wrong. Since it's a Future
, you need to await
it as follows (also, I changed the type):
final Organisation? org = await readOrganisationById(organisationId);
if (org != null) {
print(org.name);
}