0

why does this Dart have issue with return class variable, but can return a copy of it? Error message: "A value of type 'Database?' can't be returned from the function 'database' because it has a return type of 'Future'."

Note this question is focused on why the issue does not arise for Scenario 1. (i.e. question is NOT why Scenario 2 has an issue, but rather why Scenario 1 does not seem to have the issue)

import 'package:sqflite/sqflite.dart';

class DatabaseHelper {
  static final DatabaseHelper instance = DatabaseHelper._privateConstructor();
  static Database? _database;

  DatabaseHelper._privateConstructor();

  Future<Database> get database async {
    
    // Scenario 1 - Works
    Database? testDb = _database;
    if (testDb != null) return testDb;

    // Scenario 2 - Does NOT work??
    if (_database != null) return _database;   // "A value of type 'Database?' can't be returned from the function 'database' because it has a return type of 'Future<Database>'."

    Database? instance = await _initDatabase();
    _database = instance;
    return instance;
  }


  Future<Database> _initDatabase() async {
    Database _db = await openDatabase('my_db.db');
    return _db;
  }

}

Image

enter image description here

Greg
  • 34,042
  • 79
  • 253
  • 454
  • One case works because local variables can be type-promoted and non-local variables cannot. See: https://dart.dev/tools/non-promotion-reasons – jamesdlin Oct 25 '21 at 04:04
  • @jamesdlin - thanks very much for pointing this out - I was really wondering why – Greg Oct 25 '21 at 06:30

1 Answers1

0

I think the problem you are having is about a nullable return. Dart isn't validating nullable class variables after if statements, but if you insert a null check operator after the return _database, your code should works.

Ex.:

if (_database != null) return _database!;
  • just wondering though why the error/warning doesn't get displayed for "testDb" however as it's also nullable? – Greg Oct 25 '21 at 04:21