รายชื่อ tuples ใน flutter / dart

Oct 09 2020

ฉันต้องการรายชื่อ tuples ใน dart / flutter วนซ้ำและอ่านตัวแปรตัวแรกและตัวที่สอง มีแพ็คเกจ pub.devที่สร้างทูเพิลในกระพือปีก มีวิธีอื่นในโผ? ฉันจำเป็นต้องใช้ชั้นเรียนเพื่อสร้างทูเพิลเหมือนที่แพ็คเกจกระพือปีกหรือไม่?

ฉันเริ่มสร้างตัวอย่างในแผ่นปาเป้า

void main() {
  List testList = [("a",1),("b",2),("c",3),("d",4),("e",5)];
  
  
  for (var i = 0; i < 5; i++) {
    print('hello $i');
    currentItem = testList[i];

  }
}

คำตอบ

5 julemand101 Oct 09 2020 at 15:53

ตัวอย่างวิธีที่คุณสามารถวนซ้ำคู่ข้อมูลของคุณโดยใช้Mapโครงสร้างข้อมูลเป็น:

void main() {
  final testMap = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5};

  for (final mapEntry in testMap.entries) {
    final key = mapEntry.key;
    final value = mapEntry.value;

    print('Key: $key, Value: $value');
    // Key: a, Value: 1
    // Key: b, Value: 2
    // Key: c, Value: 3
    // Key: d, Value: 4
    // Key: e, Value: 5
  }
}

นอกจากนี้คุณยังสามารถแนะนำPairคลาสของคุณเองได้อย่างง่ายดายซึ่งช่วยให้คุณสามารถผูกวัตถุสองชิ้นเข้าด้วยกัน:

class Pair<T1, T2> {
  final T1 a;
  final T2 b;

  Pair(this.a, this.b);
}

void main() {
  final testList = [
    Pair("a", 1),
    Pair("b", 2),
    Pair("c", 3),
    Pair("d", 4),
    Pair("e", 5)
  ];

  for (final pair in testList) {
    print('${pair.a} -> ${pair.b}');
  }
  // a -> 1
  // b -> 2
  // c -> 3
  // d -> 4
  // e -> 5
}

ในกรณีส่วนใหญ่ฉันจะแนะนำให้คุณสร้างความclassต้องการเฉพาะสำหรับคุณเนื่องจากมันทำให้ง่ายต่อการสร้างรหัสปลอดภัย

3 jamesdlin Oct 09 2020 at 22:34

หากคุณต้องการใช้package:tupleคุณสามารถทำได้:

void main() {
  var testList = <Tuple2<String, int>>[
    Tuple2("a", 1),
    Tuple2("b", 2),
    Tuple2("c", 3),
    Tuple2("d", 4),
    Tuple2("e", 5),
  ];
  
  for (var tuple in testList) {
    print('current tuple: (${tuple.item1}, ${tuple,item2})');
  }
}