Asynchronous 颤振异步编程

Asynchronous 颤振异步编程,asynchronous,firebase-realtime-database,flutter,dart,Asynchronous,Firebase Realtime Database,Flutter,Dart,使用数据集后,我想检查有多少数据集未使用。如果我高于阈值,我想获取新数据 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 questio

使用数据集后,我想检查有多少数据集未使用。如果我高于阈值,我想获取新数据

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();
}
但是,我在调用
for(问题中的var q)时遇到以下错误{
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

您的问题是
questions
为空,因此尝试对其进行迭代将抛出错误

查看您的代码,错误的根源似乎来自您的
\u fetchFromFirebase
方法。在本例中,调用
databaseReference.one()
,然后在
部分将结果分配给
questionJson
。但是,在这个调用中,您永远不会等待
,因此,
\u fetchFromFirebase
方法在调用完成后立即返回
questionJson
的值,而不会等待调用完成。此时,
questionJson
将为空,因此返回的是空值

一般来说,我建议不要将
Future.then.catchError
模式与
async/await
模式混合使用,因为这会导致混淆逻辑,从而隐藏实际发生的事情。因此,我建议只使用
async/await
,如下所示:

\u fetchFromFirebase()异步{
试一试{
最终快照=等待databaseReference.once();
final questionJson=wait snapshot.value;
返回问题;
}捕获(e){
印刷品(e);
返回null;
}
}
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