我正在尝试从Sqflite获取数据,之前我已经成功使用过脚本,但是这次我的脚本不起作用,不同之处在于这次我必须将数据库放入资产文件中,然后我尝试将其移至“数据库”文件夹,然后使用它,
我的问题是第13行:
DbStudentManager._();
每当我取消注释时,就会出现错误,指出DbStudentManager类没有默认构造函数
final DbStudentManager dbmanager = new DbStudentManager();
以上代码在不同的小部件中生成错误
import 'dart:async';
import 'dart:io';
import 'package:path/path.dart';
import 'package:flutter/services.dart';
import 'package:sqflite/sqflite.dart';
import 'package:flutter/foundation.dart';
class DbStudentManager {
Database _database;
static final _instance = DbStudentManager._();
static get instance => _instance;
Completer<Database> _completer;
DbStudentManager._();
Future<Database> get database async {
if (_completer == null) {
_completer = Completer();
_openDatabase();
}
return _completer.future;
}
Future _openDatabase() async {
final databasesPath = await getDatabasesPath();
final path = join(databasesPath, 'st.db');
final exists = await databaseExists(path);
if (!exists) {
print("Creating new copy from asset");
try {
await Directory(dirname(path)).create(recursive: true);
} catch (_) {}
// Copy from asset
ByteData data = await rootBundle.load(join("assets", "st.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");
}
final _database = await openDatabase(path);
_completer.complete(database);
Future<List<Reslt>> getStudentList() async {
await _openDatabase();
final List<Map<String, dynamic>> maps = await _database
.rawQuery('SELECT * FROM wshakan ORDER BY id LIMIT 10');
//await _database.query('localsongs', orderBy: "id DESC");
return List.generate(maps.length, (i) {
return Reslt(
id: maps[i]['id'],
wsha: maps[i]['wsha'],
favd: maps[i]['who'],
);
});
}
}
}
class Reslt {
int id;
String wsha;
int favd;
Reslt(
{@required this.wsha,
@required this.favd,
this.id});
Map<String, dynamic> toMap() {
return {
'wsha': wsha,
'mana': mana,
'favd': favd,
};
}
}