【问题标题】:Flutter add item to list颤振将项目添加到列表
【发布时间】:2019-08-19 09:31:46
【问题描述】:

我想将一个项目添加到列表中:

void submitAll() async {
List<UserSearchItem> userSearchItems = [];
Firestore.instance
    .collection('insta_users')
    .snapshots()
    .listen((data) =>
    data.documents.forEach((doc){
      print(data.documents.length);

      User user = new User.fromDocument(doc);
      UserSearchItem searchItem = new UserSearchItem(user);
      userSearchItems.add(searchItem);
      print(user.bio);

    }));
print("Loaded");
print(userSearchItems.length);
}

但是如果我将列表的长度打印到控制台,它总是说,列表是 0 长...

print(userSearchItems.length);

有什么建议吗?

最好的问候

【问题讨论】:

  • 是否在 `userSearchItems.add(...)' 帮助周围使用setState(() {});
  • 不,那不行。

标签: list flutter google-cloud-firestore


【解决方案1】:

我将尝试解释这里发生的事情,看看这段代码:

import 'dart:async';

void main() {
  List<int> userSearchItems = [];

  Timer _sendTimeOutTimer;

  const oneSec = Duration(seconds: 2);
  _sendTimeOutTimer = Timer.periodic(oneSec, (Timer t) {
    userSearchItems.add(1);
    print(userSearchItems.length); // result 1 and it will be executed after 2 seconds 
    _sendTimeOutTimer.cancel();
  });

  print(userSearchItems.length); // result 0 and it will be executed first
}

异步动作(定时器)内的打印将在 2 秒后执行意味着在异步动作结束后,但异步动作(定时器)之外的打印将直接执行而无需等待 2 秒,在您的情况下异步操作正在侦听数据.listen((data) =&gt;,因此如果您在异步操作之外打印长度,您将看不到延迟,因为该项目尚未添加。

解决方法:你可以创建一个返回Future的函数,然后等到它完成再打印长度。

List<UserSearchItem> userSearchItems = [];

Future<String> submitAll() async {

Firestore.instance
    .collection('insta_users')
    .snapshots()
    .listen((data) =>
    data.documents.forEach((doc){
      print(data.documents.length);

      User user = new User.fromDocument(doc);
      UserSearchItem searchItem = new UserSearchItem(user);
      userSearchItems.add(searchItem);
      print(user.bio);

      return 'success';
    }));
}

void yourFunction() async{
   await submitAll();
   print("Loaded");
   print(userSearchItems.length);
}

然后拨打yourFunction()

【讨论】:

  • 感谢您的解释!当我尝试您改进的代码时,它会抛出“等待表达式只能在异步函数中使用。”任何想法?谢谢!
  • 将所有内容包装在异步函数中,我已经更新了代码示例。
  • 感谢您的帮助!但现在我得到另一个错误:“[Unhandled Exception: NoSuchMethodError: The getter 'length' was called on null.”有什么建议吗?
  • 当然可以,因为userSearchItems 应该在submitAll 函数之外声明,以便可以从yourFunction 访问,我更新了代码。
  • 好的,所以这个错误消失了 :) 但它发生了另一个错误:“未处理的异常:NoSuchMethodError:方法 'add' 在 null 上被调用。”很抱歉打扰您,但您似乎知道自己在说什么!
【解决方案2】:

添加项目后尝试在 forEach 中添加print(userSearchItems.length);,您将看到实际长度。

【讨论】:

  • 这行得通,但是在循环之外没有解决方案吗?
猜你喜欢
  • 1970-01-01
  • 2020-05-25
  • 2020-02-06
  • 2020-06-13
  • 2019-10-19
  • 2022-10-01
  • 1970-01-01
  • 2021-09-19
  • 1970-01-01
相关资源
最近更新 更多