英文:
Getting an error in the database helper class: LateInitializationError: Field '_db@382359948' has not been initialized
问题
这是我的数据库助手类。我在这一行DatabaseHelper._internal();中遇到了错误,错误信息如下:
非空实例字段'_db'必须初始化。 (文档)
尝试添加初始化表达式,或在此构造函数中添加字段初始化程序,或将其标记为'late'。
如果我将`Database _db;`更改为`late Database _db;`,那么会显示以下错误:
E/flutter (10954): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] 未处理的异常:LateInitializationError:字段'_db@382359948'尚未初始化。
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)
<异步悬挂>
这是我的数据库助手类:
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()函数,如果有任何错误或其他问题,请告诉我。谢谢。
英文:
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.
答案1
得分: 0
You need to make _db nullable for null check,
Database? _db;
More about null-safety.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论