list - 如何迭代一个类?
问题描述
更新
这是我的最终代码,以防万一有人需要它:
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'),
];
解决方案
您可以迭代recyclable
列表的一种方法是使用forEach方法
recyclable.forEach((item){
if(item.title == _outputs[0]["label"]){
//your code for when the match is found
}
});
推荐阅读
- json - 如何在 Flutter 中从 JSON 中提取独特的类别?
- jquery - 合并多个无序列表项并将它们转换为选择下拉列表
- firebase - Firebase 云功能:使用事务更新函数中的代码后出现“无法获取默认凭据”错误
- heroku - Heroku部署应用程序错误无法打开应用程序
- ruby-on-rails - ActiveRecord::StatementInvalid (SQLite3::SQLException: no such table: main.contacts) Rails 中的友谊
- arrays - 加入两个字符串 - Swift
- pine-script - 如何只执行一次strategy.entry order,然后等待条件重新进入
- python - 自定义 tensorflow-lite 模型推理提供 1.00 的测试精度
- javascript - 中继 JS 异常:预期请求具有有效的 `id` 或 `cacheID` 属性
- azure-functions - 如何在 Azure Function 中运行通过 NPM 安装的命令