使用数据集后,我想检查有多少数据集未使用。如果我超过阈值,我想要获取新的数据。
useQuestion(Question question) async {
print("using question $question");
question.used=1;
final db = await database;
int count = await db.rawUpdate(
'UPDATE Question SET used = ? WHERE question = ?',
[question.used,question.question]);
print(question);
print("Made $count changes");
var questions = await _checkQuestionThreshold();
print(questions);
for (var q in questions) {
newQuestion(Question.fromJson(q));
}
}检查门限
_checkQuestionThreshold() async {
print("count questions...");
final db = await database;
var res = await db.query("Question");
int count = Sqflite.firstIntValue(
await db.rawQuery('SELECT COUNT(*) FROM Question'));
int countUsed = Sqflite.firstIntValue(
await db.rawQuery('SELECT COUNT(*) FROM Question where used="1"'));
int i = 0;
if (count < 1 || (countUsed / count) < 0.5) {
print("Okay... we fetch new...");
return await _fetchFromFirebase();
}从DB中获取:
_fetchFromFirebase() async {
var questionJson;
databaseReference.once().then((DataSnapshot snapshot) async {
questionJson = await snapshot.value;
}).catchError((e) {
print(e);
});
return questionJson;
}但是,当调用for (var q in questions) { newQuestion(Question.fromJson(q)); }时,我会得到以下错误,我想知道我到底遗漏了什么。
I/flutter ( 5150): count questions...
I/flutter ( 5150): Okay... we fetch new...
I/flutter ( 5150): null
E/flutter ( 5150): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: NoSuchMethodError: The getter 'iterator' was called on null.
E/flutter ( 5150): Receiver: null发布于 2019-11-19 22:29:55
您的问题是questions是空的,所以试图迭代它将引发一个错误。
看看您的代码,错误的根源似乎来自您的_fetchFromFirebase方法。在本例中,调用databaseReference.once(),在then部分将结果分配给questionJson。但是,在这个调用中您从不使用await,因此_fetchFromFirebase方法在调用完成后立即返回questionJson的值。此时,questionJson将为null,因此这就是返回的内容。
通常,我建议不要将Future.then.catchError模式与async/await模式混为一谈,因为它可能导致混淆逻辑,从而隐藏实际发生的事情。因此,我建议只坚持这样的async/await:
_fetchFromFirebase() async {
try {
final snapshot = await databaseReference.once();
final questionJson = await snapshot.value;
return questionJson;
} catch (e) {
print(e);
return null;
}
}https://stackoverflow.com/questions/58942689
复制相似问题