我正在使用 SQFLite 将数据存储在flutter应用程序中。数据库提供者是
class MessageDatabaseProvider {
Database db;
Future open() async {
final path = join(await getDatabasesPath(), databaseName);
db = await openDatabase(
path,
version: 1,
onCreate: (Database db, int version) async {
await db.execute('''
create table $tableMessage (
$columnId integer primary key autoincrement,
$columnCountryCode text not null,
$columnPhoneNumber text not null,
$columnMessage text null,
$columnCreated integer null)
''');
}
);
}
Future<List<Message>> list() async {
List<Map> maps = await db.query(tableMessage,
columns: [columnId, columnCountryCode, columnPhoneNumber, columnMessage, columnCreated],
orderBy: columnId
);
List<Message> list = [];
maps.forEach((element) {
list.add(Message.fromMap(element));
});
return list;
}
}
并构建一个 ListView
class _MessageHistoryListState extends State<MessageHistoryList> {
final _database = MessageDatabaseProvider();
@override
Widget build(BuildContext context) {
return Center(
child: _buildMessageHistory(),
);
}
Widget _buildMessageHistory() {
_database.open();
return FutureBuilder<List>(
future: _getList(),
initialData: [],
builder: (context, snapshot) {
print(snapshot);
return snapshot.hasData ?
ListView.builder(
padding: EdgeInsets.all(16.0),
itemCount: snapshot.data.length,
itemBuilder: (context, i) {
return _buildRow(snapshot.data[i]);
},
)
: Center(
child: CircularProgressIndicator(),
);
},
);
}
}
它第一次显示项目列表,然后在更改导航后出现错误
AsyncSnapshot<List<dynamic>>(ConnectionState.done, null, NoSuchMethodError: The method 'query' was called on null.
答案 0 :(得分:0)
在使用以下行将其关闭之前,您无法使用openDatabase
await db.close();
如果不重新创建窗口小部件,则应从 _database.open();
调用init()
。从_database.open();
_buildMessageHistory()