【问题标题】:How to iterate a class?如何迭代一个类?
【发布时间】:2020-12-04 23:31:42
【问题描述】:

更新

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

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'),
];

【问题讨论】:

  • 请发布一个最小的、完整的、可验证的示例。用波浪线张贴截图不是很有用;你没有指出给出了什么错误。
  • 不清楚您要做什么。
  • @jamesdlin 我添加了更多信息来澄清我的问题。感谢您的评论。
  • @JigarPatel 我添加了更多信息来澄清我的问题。感谢您的评论。
  • 您仍然没有解释错误是什么(将鼠标光标悬停在带有红色波浪线的文本上,或者只是手动运行dartanalyzer),您仍然没有提供最小的,完整的、可验证的示例,其他人可以使用它来重现您遇到的任何内容。

标签: list class flutter


【解决方案1】:

您可以遍历recyclable 列表的一种方法是使用forEach 方法

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

【讨论】:

  • 感谢您的评论。不幸的是,forEach 带有红色下划线,并声明它不是为 Recyclable 类型定义的。
  • 看来你一定是错误地在Recyclable 类上调用了它。您需要调用列表recyclable 上的forEach 方法。所以“可回收”用小写“r”而不是大写“R”。
猜你喜欢
  • 1970-01-01
  • 2016-03-22
  • 2012-07-14
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 2021-12-06
  • 2019-03-23
  • 2015-04-28
相关资源
最近更新 更多