Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using Flutter to read a single record from SQFlite, checking for null

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading