dart 在数据库帮助器类中获取错误:延迟初始化错误:字段“_db@382359948”尚未初始化

uqdfh47h  于 2023-03-10  发布在  其他
关注(0)|答案(1)|浏览(163)

下面是我的数据库助手类,我在DatabaseHelper._internal();这一行中遇到错误,错误指出:

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>

这是我的数据库助手类:

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 {...}
}

也请通过这个函数syncDataFromFirestore(),如果有任何错误或其他错误,然后请告诉我。谢谢。

vfhzx4xs

vfhzx4xs1#

您需要使_db可为空以进行空检查,

Database? _db;

更多关于null-safety的信息。

相关问题