0

My team and I are currently in the process of trying to port an older Android project over to Flutter and are having issues with the Dart null checker in our DatabaseService class.

Using a number of resources we found on Google, the class currently is defined as:

import 'dart:async';
import 'package:logging/logging.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

import 'package:agineek/models/player.dart';

class DatabaseService {
  static const _dbName = 'agineek.db';
  static final DatabaseService _instance = DatabaseService._internal();
  static Database _db;

  factory DatabaseService() => _instance;

  final Logger log = Logger('Database');

  DatabaseService._internal();

  Future<Database?> get db async {
    if(_db != null) {
      return _db;
    }

    // ignore: join_return_with_assignment
    _db = await _openDatabase();

    return _db;
  }

  /// Open a connection to the [Database] and perform
  /// database creation transactions.
  Future<Database> _openDatabase() async {
    final dbPath = await getDatabasesPath();
    final database = await openDatabase(
      join(dbPath, _dbName),
      version: 1,
      onCreate: (Database db, int version) async {
        await db.execute('''
        create table ${Player.tableName} (
          ${Player.columnPlayerId} integer primary key autoincrement,
          ${Player.columnPlayerHitColor} text not null
        );
        ''');
      }
    );

    return database;
  }

  /// Create a [Player] entry in the database.
  /// Conflicts are resolved as a replace action.
  Future<Player> createPlayer(Player player) async {
    final database = _db;
    player.id = await database.insert(
      Player.tableName,
      player.toMap(),
      conflictAlgorithm: ConflictAlgorithm.replace
    );

    return player;
  }

  ... a bunch of other boilerplate transactions
}

However, we're stuck with trying to figure out why the static _db is being flagged as a dart(not_initialized_non_nullable_variable) error.

Any assistance would be appreciated.

Joseph Quinn
  • 101
  • 5

1 Answers1

0

Try adding the late keyword as such:

static late Database _db;

But that would require some extra changes I guess. So an alternative would be to make it nullable:

static Database? _db;
Robert Sandberg
  • 6,832
  • 2
  • 12
  • 30