如何在Flutter中使用集合for循环? [英] How do I use collection for-loops in Flutter?

查看:2003
本文介绍了如何在Flutter中使用集合for循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用 for 循环在 SliverList 中添加小部件。

但是出现以下错误:

I am trying to add widgets in a SliverList using a for-loop.
But I get the following error:


错误:无法将元素类型 Set分配给列表类型 Widget

error: The element type 'Set' can't be assigned to the list type 'Widget'

这里出现问题:

slivers: [
  for(int i=0; i < 5; i++) {
    EachBusInfoBodyWidget(Colors.green)
  }
]


推荐答案

这里的问题是运算符集合不带花括号( {} )。也就是说,它们不能与它们配合使用。

弯括号用于 Set Map 文字。如果在条目后面添加冒号,它将成为 Map 文字,例如 {味道:甜} 。但是,如果仅使用花括号,则会创建 Set 。通常,这不影响for循环,因为花括号被用作常规流控制。

The problem here is that the collection for operator does not take curly braces ({}). i.e. they do not work with them as you can tell.
Curly braces are used for Set and Map literals. If you add a colon behind an entry, it becomes a Map literal, e.g. { 'flavor': 'sweet' }. However, if you just use curly braces, it creates a Set. Usually this does not affect for-loops because curly braces are used as regular flow control.

无论如何,要解决此问题,您只需要删除花括号即可:

Anyways, to fix the issue you simply need to remove your curly braces:

for(var i = 0; i < 5; i++) EachBusInfoBodyWidget(Colors.green)

这篇关于如何在Flutter中使用集合for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆