首页 > 解决方案 > 如何迭代一个类?

问题描述

更新

这是我的最终代码,以防万一有人需要它:

int index = -2; //I am not 100% sure why I need to start -2, but  I assume that `forEach((item){})` probably increase `index` by one, and I also increase `index` inside of the loop, so that's probably why.

    recyclable.forEach((item) {
      index++;
      if (item.title == _outputs[0]["label"]) {
        //your code for when the match is found
        //move to the detailed page to show more description
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => DetailScreen(recyclable: recyclable[index]),
          ),
        );
      }
    }

更新结束

我创建了一个名为 的类Recyclable,并使用该类创建了一个名为 的列表recyclable。该列表recyclable有一个名为 的字符串title,我正在尝试对其进行迭代title以找到与_outputs[0]["label"].

为此,我尝试了以下代码:

    while (_outputs[0]["label"] != recyclable[index].title) {
      index++;
    }

不知何故,有一个红色下划线index,我不知道为什么。

我还尝试for loop如下通过index从我的代码中删除来删除红色下划线:

    for (var _outputs[0]["label"] in recyclable.title) {
      index++;
    }

但是代码似乎完全关闭了。

仅供参考,这是我的课Recyclable

class Recyclable {
  final String title;
  final String description;
  final String instruction;
  final String why;
  final String
      recycle; //put either "recyclable" or "not recyclable" (This item "can be recycled")
  final String
      donate; //put either "can be donated" or "cannot be donated" (This item "can be donated")

  Recyclable(this.title, this.description, this.instruction, this.why,
      this.recycle, this.donate);
}

这是list

List<Recyclable> recyclable = [
Recyclable('PAPERS', 'abc2', 'instruction123', 'why123', 'recyclable',
      'cannot be donated'),
  Recyclable('CLOTHING', 'abc3', 'instruction123', 'why123', 'recyclable',
      'can be donated'),
  Recyclable('CARDBOARDS', 'abc4', 'instruction123', 'why123',
      'can be recycled', 'cannot be donated'),
  Recyclable('COMPUTERS', 'abc4', 'instruction123', 'why123', 'recyclable',
      'can be donated'),
];

标签: listclassflutter

解决方案


您可以迭代recyclable列表的一种方法是使用forEach方法

  recyclable.forEach((item){
    if(item.title == _outputs[0]["label"]){
      //your code for when the match is found
    }
  });

推荐阅读