首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >颤振异步编程

颤振异步编程
EN

Stack Overflow用户
提问于 2019-11-19 20:58:14
回答 1查看 54关注 0票数 0

使用数据集后,我想检查有多少数据集未使用。如果我超过阈值,我想要获取新的数据。

代码语言:javascript
复制
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));
      }
  }

检查门限

代码语言:javascript
复制
_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中获取

代码语言:javascript
复制
_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)); }时,我会得到以下错误,我想知道我到底遗漏了什么。

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-11-19 22:29:55

您的问题是questions是空的,所以试图迭代它将引发一个错误。

看看您的代码,错误的根源似乎来自您的_fetchFromFirebase方法。在本例中,调用databaseReference.once(),在then部分将结果分配给questionJson。但是,在这个调用中您从不使用await,因此_fetchFromFirebase方法在调用完成后立即返回questionJson的值。此时,questionJson将为null,因此这就是返回的内容。

通常,我建议不要将Future.then.catchError模式与async/await模式混为一谈,因为它可能导致混淆逻辑,从而隐藏实际发生的事情。因此,我建议只坚持这样的async/await

代码语言:javascript
复制
_fetchFromFirebase() async {
  try {
    final snapshot = await databaseReference.once();
    final questionJson = await snapshot.value;
    return questionJson;
  } catch (e) {
    print(e);
    return null;
  }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58942689

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档