我想从资产访问数据库,但出现此错误
NoSuchMethodError(NoSuchMethodError:方法“ rawQuery”在null上调用。
接收者:null
尝试致电:rawQuery("SELECT * FROM productss")
)
import 'dart:io';
import 'package:path/path.dart';
import 'dart:typed_data';
import 'package:flutter/services.dart';
import 'package:sqflite/sqflite.dart';
class DatabaseHelper2{
static final DatabaseHelper2 _instance = DatabaseHelper2.internal();
factory DatabaseHelper2() =>_instance;
var oneSecond = Duration(seconds: 5);
static Database _db;
Future<Database> get db async{
if(_db != null){
print("database does");
return _db;
}
_db = await initDbs();
print("database doesnt");
return _db;
}
DatabaseHelper2.internal();
initDbs() async{
// Construct a file path to copy database to
var databasesPath = await getDatabasesPath();
var path = join(databasesPath, "productss.db");
// Check if the database exists
var exists = await databaseExists(path);
if (!exists) {
// Should happen only the first time you launch your application
print("Creating new copy from asset");
// Make sure the parent directory exists
try {
await Directory(dirname(path)).create(recursive: true);
} catch (_) {}
// Copy from asset
ByteData data = await rootBundle.load(join("assets", "productss.db"));
List<int> bytes =
data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
// Write and flush the bytes written
await File(path).writeAsBytes(bytes, flush: true);
} else {
print("Opening existing database");
}
// open the database
_db = await openDatabase(path);
}
void productDb2(Database database, int version)async{
await database.execute("""
CREATE TABLE productss
(
id INTEGER PRIMARY KEY,
name TEXT,
price INTEGER,
size INTEGER,
fat100 INTEGER,
carbs100 INTEGER,
protein100 INTEGER,
dateCreated String
)
""");
}
Future<List> getProductsdb()async{
var dbClient = await db;
var result = await dbClient.rawQuery("SELECT * FROM productss");
return result.toList();
}
}
我不知道为什么会这样。 数据库不为空。我检查了。
答案 0 :(得分:0)
您正在尝试await db
,但是类属性被命名为_db
。 IDE是否没有捕获到此错误?