【问题标题】:LateInitializationError: Field '_database@29391942' has not been initializedLateInitializationError:字段 \'_database@29391942\' 尚未初始化
【发布时间】:2023-01-03 15:36:11
【问题描述】:

我有一个将数据插入数据库的 Flutter 应用程序。 它从数据库中获取并显示数据。

但我得到了一个 *延迟初始化错误.

我认为原因在于 >
静态后期数据库_database;

错误 :

E/flutter ( 6700): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: 
LateInitializationError: Field '_database@29391942' has not been initialized.

代码:

class ProductDBHelper{

  static final _databaseName = 'mydb.db';
  static final _databaseVersion = 1;


  static final _table_products = 'products';
  static late String path;

  ProductDBHelper._privateConstructor();
  static final ProductDBHelper instance = ProductDBHelper._privateConstructor();

  static late Database _database;


  //// Check whether the database created or not.
  Future get database async{

    if(_database != null) return _database;

    _database = await _initDatabase();
    print('Database : $_database');
    return _database;
    
  }
  //// Initialise database with local file path , db name.
  _initDatabase() async{
    
    Directory documentDirectory = await getApplicationDocumentsDirectory();
    //// localstorage path/databasename.db
    String path = join(documentDirectory.path , _databaseName);
    return await openDatabase(
      path,
      version: _databaseVersion,
      onCreate: _onCreate);

  }
  //// on Create for creating database.
  Future _onCreate(Database db, int version) async{

    await db.execute('CREATE TABLE $_table_products(id INTEGER PRIMARY KEY autoincrement, name TEXT, price TEXT, quantity INTEGER)');
  }

  static Future getFileData(){
    return getDatabasesPath().then((value)
    {
      return path = value;
    }
    );
  }

  Future insertProduct(Product product) async{

    Database db = await instance.database;
    return await db.insert(
        _table_products, Product.toMap(product),
        conflictAlgorithm: ConflictAlgorithm.ignore
    );
  }

谁能建议我解决这个错误?

【问题讨论】:

    标签: database flutter dart dart-null-safety sqflite


    【解决方案1】:

    当您进行空检查时,

        if(_database != null) return _database;
    

    您需要将数据类型设置为可为空, 代替

      static late Database _database;
    

      static  Database? _database;
    

    【讨论】:

      猜你喜欢
      • 2023-03-17
      • 1970-01-01
      • 2022-07-27
      • 2021-10-27
      • 2021-12-29
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多