【问题标题】:Why is the list length 0? Why is data not being added?为什么列表长度为 0?为什么没有添加数据?
【发布时间】:2020-03-27 12:41:10
【问题描述】:

我正在尝试使用从 firebase 获取的数据填充列表,但由于某种原因,列表的长度为零。我正在将记录添加到 forEach 内的 weekExpenses 列表中。当我打印在 forEach 中检索到的数据和列表的长度时,它存在并且长度是正确的,但是当我从外部打印列表的长度时,它的长度为 0。数据存在于 cloud firestore 中。在 cmets 中,我指出了一切正常的地方以及问题所在。有人可以帮忙吗。

getThisWeekExpenditure() async{
  List<WeekExpense> weekExpenses = new List<WeekExpense>();

  var day;
  var todayDate;
  int weekDay;

  for (int i = 0; i < DateTime.now().weekday; i++) {
    weekDay = DateTime.now().weekday;
    day = (DateTime.now().day - i).toString();
    todayDate = day +
        "-0" +
        DateTime.now().month.toString() +
        "-" +
        DateTime.now().year.toString();

    int totalExpenditure = 0;

    //get the expenses for each day and sum them
    await reference
        .document(userId)
        .collection(todayDate)
        .document('Expenses')
        .collection('Expenses')
        .snapshots()
        .forEach((QuerySnapshot snapshot) {
      for (var doc in snapshot.documents) {
        if (doc.data.containsKey('Price')) //this is true
        {
          var price = doc.data['Price'];
          totalExpenditure = totalExpenditure + price;
        } else {
          totalExpenditure = totalExpenditure + 0;
        }
      }

      var weekExpense = WeekExpense(
          weekDay: DateUtils().getWeekDayName(weekDay - i),
          expenditure: totalExpenditure,
          barColor: i % 2 == 0
              ? charts.ColorUtil.fromDartColor(Colors.orange[900])
              : charts.ColorUtil.fromDartColor(Colors.purple));

      //this shows the weekdays
      print("length ${weekExpenses.weekDay}");

      weekExpenses.add(weekExpense);

      //this shows the lengths of 1,2,3,4,5 records. Which is okay
      print("length ${weekExpenses.length}");

      if (i == DateTime.now().weekday) {
        totalExpenditure = 0;
      }
    });
  }
  //But at this point when i check the length its 0.
  print("length ${weekExpenses.length}");

  return weekExpenses;
}

我如何调用它来测试

    RaisedButton(
      onPressed: () {
         DatabaseService(userId: user.uid).getThisWeekExpenditure();
      },
    )

抛出的错误

    ════════ Exception caught by gesture ═══════════════════════════════════════════════════════════════
The following NoSuchMethodError was thrown while handling a gesture:
Class 'Future<dynamic>' has no instance getter 'length'.
Receiver: Instance of 'Future<dynamic>'
Tried calling: length

When the exception was thrown, this was the stack: 
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
#1      _StatisticsState.build.<anonymous closure> (package:expensetracker/screens/statistics/statistics.dart:179:38)
#2      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:706:14)
#3      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:789:36)
#4      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
...
Handler: "onTap"
Recognizer: TapGestureRecognizer#6e788
  debugOwner: GestureDetector
  state: ready
  won arena
  finalPosition: Offset(158.3, 519.5)
  finalLocalPosition: Offset(158.3, 25.5)
  button: 1
  sent tap down

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    reference.document 是异步的。你必须让你的函数 asyncawait 那个调用。现在,您的 print("length ${weekExpenses.length}"); 会在您填充列表之前被调用。

    【讨论】:

    • 感谢您的回答。我按照你说的做了,但是没有用。最后一次打印没有被执行,循环只运行一次
    • 是否抛出错误?就这样我们在同一页面上,我的意思是让你像这样打电话给getThisWeekExpendituregetThisWeekExpenditure() async {/*...*/} 并在reference.document(userId).collection(todayDate)... 之前添加一个await
    • 是的。像这样 Future> 使函数成为未来,并且循环运行一次。当我执行 getThisWeekExpenditure() async {/*...*/} 而不添加 Future 类型时,它会引发错误 Class 'Future' has no instance getter 'length'。
    • 是的,使函数异步使任何返回值成为Future&lt;value&gt;。我想知道您是否可以使用当前正在执行的操作以及您如何使用getThisWeekExpenditure 以及引发的完整错误来更新您的代码。另外你怎么知道 for 循环只运行一次?我只是好奇你是在调试器中单步执行它还是在其他东西中
    • 我已经更新了我的代码。我知道循环在单步执行后会运行一次
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多