LateInitializationError: Field ‘_db@382359948’ has not been initialized.

huangapple go评论124阅读模式
英文:

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 &#39;_db&#39; must be initialized. (Documentation)
Try adding an initializer expression, or add a field initializer in this constructor, or mark it &#39;late&#39;.

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 &#39;_db@382359948&#39; 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): &lt;asynchronous suspension&gt;

This is my Database Helper Class:

import &#39;package:cloud_firestore/cloud_firestore.dart&#39;;
import &#39;package:sqflite/sqflite.dart&#39;;

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

  static final DatabaseHelper _instance = DatabaseHelper._internal();

  factory DatabaseHelper() =&gt; _instance;

  DatabaseHelper._internal();

  Database _db;

  Future&lt;Database&gt; get db async {
    if (_db == null) {
      _db = await _initDatabase();
    }
    return _db;
  }

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

  Future&lt;void&gt; syncDataFromFirestore() async {
    final QuerySnapshot&lt;Map&lt;String, dynamic&gt;&gt; snapshot =
        await FirebaseFirestore.instance.collection(&#39;recipes&#39;).get();

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

  Future&lt;void&gt; syncData() async {...}

  Future&lt;List&lt;int&gt;&gt; getAllRecipeID() async {...}

  Future&lt;List&lt;Map&lt;String, dynamic&gt;&gt;&gt; getAllRecipe() async {...}

  Future&lt;List&lt;Map&lt;String, dynamic&gt;&gt;&gt; getRecipe(int id) async {...}

  Future&lt;int&gt; updateRecipe(Map&lt;String, dynamic&gt; recipe) async {...}

  Future&lt;int&gt; 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.

英文:

You need to make _db nullable for null check,

Database? _db;

More about null-safety.

huangapple
  • 本文由 发表于 2023年3月9日 18:33:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75683388.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定