我试图使用我在数据库类中创建的插入函数,但它只返回以下错误"NoSuchMethodError:对null调用了方法"insert"我不知道为什么,我正在Youtube上学习成长发育者的教程,他似乎没有遇到这个问题。
database_helper.dart
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
class DatabaseHelper {
static final _dbName = 'poi_database.db';
static final _dbVersion = 1;
static final _tableName = 'poi';
static final cnameId = 'id';
static final cnameVillage = 'village';
static final cnameLieu = 'lieu';
static final cnameType = 'type';
static final cnameEtat = 'etat';
static final cnameNotes = 'notes';
static final cnameLatitude = 'latitude';
static final cnameLongitude = 'longitude';
static final cnameImageUrl = 'image_url';
DatabaseHelper._privateConstructor();
static final DatabaseHelper instance = DatabaseHelper._privateConstructor();
static Database _database;
Future<Database> get database async{
if(_database != null) {
return _database;
}
else {
_database = await _initiateDatabase();
return _database;
}
}
_initiateDatabase() async {
Directory directory = await getApplicationDocumentsDirectory();
String path = join(directory.path, _dbName);
await openDatabase(path, version: _dbVersion, onCreate: _onCreate);
}
Future _onCreate(Database db, int version) async {
db.execute(
'''
CREATE TABLE $_tableName(
$cnameId INTEGER PRIMARY KEY,
$cnameVillage TEXT NOT NULL,
$cnameLieu TEXT NOT NULL,
$cnameType TEXT NOT NULL,
$cnameEtat TEXT NOT NULL,
$cnameNotes TEXT NOT NULL,
$cnameLatitude TEXT NOT NULL,
$cnameLongitude TEXT NOT NULL,
$cnameImageUrl TEXT)
'''
);
}
Future<int> insert(Map<String, dynamic> row) async {
Database db = await instance.database;
return await db.insert(_tableName, row);
}
Future<List<Map<String, dynamic>>> queryAll() async {
Database db = await instance.database;
return await db.query(_tableName);
}
Future<int> update(Map<String, dynamic> row) async {
Database db = await instance.database;
int id = row[cnameId];
return await db.update(_tableName, row, where:'$cnameId = ?', whereArgs: [id]);
}
Future<int> delete(int id) async {
Database db = await instance.database;
return await db.delete(_tableName, where: '$cnameId = ?', whereArgs: [id]);
}
}
我尝试使用它的地方:
int i = await DatabaseHelper.instance.insert({
DatabaseHelper.cnameVillage : _village,
DatabaseHelper.cnameLieu : _lieu,
DatabaseHelper.cnameType : _type,
DatabaseHelper.cnameEtat : _etatSelect,
DatabaseHelper.cnameNotes : _notes,
DatabaseHelper.cnameLatitude : markerLat,
DatabaseHelper.cnameLongitude : markerLong,
DatabaseHelper.cnameImageUrl : '',
});
提前感谢!
看起来不像是在初始化数据库。你在哪里调用getDatabase?