Search code examples
fluttersqlitedartsqflite

Getting an error in the database helper class: LateInitializationError: Field '_db@382359948' has not been initialized


Below is my database helper class I am getting error in the this line DatabaseHelper._internal(); and error states that:

Non-nullable instance field '_db' must be initialized. (Documentation)
Try adding an initializer expression, or add a field initializer in this constructor, or mark it 'late'.

If I make `Database _db;` to `late Database _db;` then it shows me this error: 
E/flutter (10954): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: LateInitializationError: Field '_db@382359948' has not been initialized.
E/flutter (10954): #0      DatabaseHelper._db (package:recipedia/Database/databaseHelper.dart)
E/flutter (10954): #1      DatabaseHelper.db (package:recipedia/Database/databaseHelper.dart:177:9)
E/flutter (10954): #2      main (package:recipedia/main.dart:18:18)
E/flutter (10954): <asynchronous suspension>

This is my Database Helper Class:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:sqflite/sqflite.dart';

class DatabaseHelper {
  final String recipeTable = 'recipes';
  final String recipeId = 'recipeId';
  final String recipeName = 'recipeName';
  final String recipeCategory = 'recipeCategory';
  final String recipeDescription = 'recipeDescription';
  final String recipeRating = 'recipeRating';
  final String recipeTime = 'recipeTime';
  final String recipeIngredients = 'recipeIngredients';
  final String recipeURL = 'recipeURL';

  static final DatabaseHelper _instance = DatabaseHelper._internal();

  factory DatabaseHelper() => _instance;

  DatabaseHelper._internal();

  Database _db;

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

  Future<Database> _initDatabase() async {
    final String path = await getDatabasesPath();
    return openDatabase(
      '$path/recipes.db',
      version: 1,
      onCreate: (db, version) {
        db.execute(
            'CREATE TABLE $recipeTable($recipeId INTEGER PRIMARY KEY, $recipeName TEXT, $recipeDescription TEXT, $recipeCategory TEXT, $recipeIngredients TEXT, $recipeURL TEXT, $recipeTime TEXT, $recipeRating INTEGER)');
      },
    );
  }

  Future<void> syncDataFromFirestore() async {
    final QuerySnapshot<Map<String, dynamic>> snapshot =
        await FirebaseFirestore.instance.collection('recipes').get();

    final Batch batch = _db.batch();
    for (final QueryDocumentSnapshot<Map<String, dynamic>> doc
        in snapshot.docs) {
      final Map<String, dynamic> data = doc.data();
      batch.insert(
        recipeTable,
        {
          recipeId: doc.id,
          recipeName: data['recipe_name'],
          recipeCategory: data['recipe_category'],
          recipeDescription: data['recipe_description'],
          recipeRating: data['recipeRating'],
          recipeTime: data['recipeTime'],
          recipeIngredients: data['recipeIngredients'],
          recipeURL: data['recipeURL'],
        },
      );
    }
    await batch.commit();
  }

  Future<void> syncData() async {...}

  Future<List<int>> getAllRecipeID() async {...}

  Future<List<Map<String, dynamic>>> getAllRecipe() async {...}

  Future<List<Map<String, dynamic>>> getRecipe(int id) async {...}

  Future<int> updateRecipe(Map<String, dynamic> recipe) async {...}

  Future<int> deleteRecipe(int id) async {...}
}

Also please go through this function syncDataFromFirestore() if there any error or something else wrong then please tell me. Thankyou.


Solution

  • You need to make _db nullable for null check,

    Database? _db;
    

    More about null-safety.