簡體   English   中英

Flutter 將項目添加到列表

[英]Flutter add item to list

我想在列表中添加一個項目:

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);

有什么建議嗎?

此致

我將嘗試解釋這里發生的事情,看看這段代碼:

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 秒,在您的情況下,異步操作是收聽 data .listen((data) => ,因此如果您在異步操作之外打印長度,您將看不到傳遞的內容,因為該項目尚未添加。

解決方案:您可以創建函數女巫返回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()

嘗試添加print(userSearchItems.length); 添加項目后,在 forEach 內部,您將看到實際長度。

有一種簡單的方法可以在 Flutter 上添加新數據列表。

for (var i = 0; i < list.length; i++) {
    double newValue=newValue+1; //This is just an example,you should put what you'r trying to add here.
    list[i]["newValueName"] = newValue; //This is how we add the new value tu the list,
  }

通過執行以下操作查看它是否有效:

print(list);//You can put a breakpoint her to see it more clearly 

希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM