簡體   English   中英

如何同時遍歷兩個列表 - Flutter

[英]How to loop through two lists at the same time - Flutter

我正在嘗試同時遍歷兩個列表

例如

List A = ['Chapter 1','Chapter 2','Chapter 3'];
List B = ['Paragraph 1','Paragraph 2','Paragraph 3'];

for(var chapter in A)  // This would itreate through only first list (A), How can I iterate through both list
children: [
     Text(chapter);   
     Text(paragraph);
]

我需要在“for”循環中同時遍歷兩個列表。

這是代碼:

  List A = ['Chapter 1','Chapter 2','Chapter 3'];
  List B = ['Paragraph 1','Paragraph 2','Paragraph 3'];
  for (int i = 0; i < A.length; i++) {
      print ("${A[i]}");
      print ("${B[i]}");
  }

如果這沒有幫助,請告訴我。

final c = zip([a, b]).map((item) => Foo(item[0], item[1])).toList();

我同意 Randal Schwartz 關於IterableZip的說明。 請注意,我找不到 Gbenga 提到的任何zip ,還請注意package:collection/iterable_zip.dart已棄用,您只需導入collection.dart ,如下所示:

import 'package:collection/collection.dart';

final A = ['Chapter 1','Chapter 2','Chapter 3'];
final B = ['Paragraph 1','Paragraph 2','Paragraph 3'];
for (final pairs in IterableZip([A, B])) {
    print(pairs[0]);
    print(pairs[1]);
}

還有一些注意事項:

  • final Afinal B變量將輸入List<String>列表,我不建議使用動態List A
  • 我沒有為IterableZip指定模板類型,但在某些情況下(在我使用它的復雜情況下)您可能需要像IterableZip<String>一樣顯式鍵入它,因此在循環中您可以更方便地訪問成員。 在這種簡單的情況下,編譯器/解釋器可以很容易地推斷出類型。
  • 其他 StackOverflow 問題中的其他一些答案提到了 quiver,但除非您需要它用於其他一些功能,否則您不必向項目添加另一個額外的包依賴項。 標准集合包有這個IterableZip

暫無
暫無

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

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