flutter - 为什么列表长度为0?为什么不添加数据?

标签 flutter dart

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

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

最佳答案

reference.document是异步的。您必须使函数asyncawait能够调用。现在,在填充列表之前,将调用print("length ${weekExpenses.length}");

关于flutter - 为什么列表长度为0?为什么不添加数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60886251/

相关文章:

Dart/flutter : String data from initState can't be passed via setState

Flutter 动画列表在动画移除项目时显示列表元素两次

firebase - 完成一个操作后如何向所有用户动态发送 FirebaseMessaging - Flutter?

dart - Dart 是否支持参数化单元测试?

android - 使用 Flutter 访问大量 JSON Assets

json - Flutter 将 json 作为字节发送到 websocket 服务器?

flutter - 使两个文本字段始终对齐

flutter - 在 Flutter 中将数据异步加载到 ChangeNotifier 模型中

function - 在 Dart 中定义函数时,如何将参数的默认值设置为 { },即空 Map?

regex - 正则表达式在imap响应中获取文件的base64字符串