元素类型“List<widget>”无法分配给列表类型“Widget”。

73

我想使用for循环在gridview中添加数据,但是出现了一些错误。这是我的组件代码:

return new GridView.count(
    crossAxisCount: 2,
    padding: const EdgeInsets.all(10.0),
    crossAxisSpacing: 10.0,
    mainAxisSpacing: 10.0,
    children: <Widget>[getList()],
);

`getList()` 代码
List<Widget> getList() {
  List<Widget> childs = [];
  for (var i = 0; i < 10; i++) {
    childs.add(new ListItem('abcd ' + $i));
  }
  return childs;
}

但是它显示编译时错误。
The element type 'List<widget>' can't be assigned to the list type 'Widget'
7个回答

109

在这里,您正在将列表包装为列表

children: <Widget>[getList()],

这应该是更好的选择

children: getList(),

24

只需使用展开运算符:

return new GridView.count(
    crossAxisCount: 2,
    padding: const EdgeInsets.all(10.0),
    crossAxisSpacing: 10.0,
    mainAxisSpacing: 10.0,
    children: <Widget>[...getList()],
);

4
谢谢,它起作用了。但是你能解释一下使用分隔符的情况吗? - Nadeem Shaikh

15

使用扩展运算符是解决这个问题的一种方法。但还有另一种方法,涉及到使用toList()方法。

children属性需要小部件列表。但在您的情况下,它变成了以下内容:

return new GridView.count(
    crossAxisCount: 2,
    padding: const EdgeInsets.all(10.0),
    crossAxisSpacing: 10.0,
    mainAxisSpacing: 10.0,
    children: [
      [
        ListItem('abcd 0'),
        ListItem('abcd 1'),
        ...
      ]
    ],
);

因此,

解决方案1

包装应为 children: getList(),

解决方案2(扩展运算符)

children: <Widget>[...getList()],

顺便提一下,当尝试使用像map()方法这样的东西时,您可能会遇到此问题。在这种情况下,使用toList()方法非常方便。例如,

children: someListOfObjects.map((el) => Text(el)).toList(),


12

我发现有两种方法可行。

方法1 - 简单

这种方法在最新版本的flutter中得到支持。

var list = ["one", "two", "three", "four"]; 

child: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
          for(var item in list ) Text(item)
      ],
),

方法2 - 稍微复杂

Flutter 1.12.13+hotfix.7Dart 2.7.0中测试,我们可以按以下方式遍历对象列表:

遍历对象列表

...data.map((f) => paragraph(f.title, f.description)).toList(),

自定义小部件

Column paragraph(String title, String description) {
  return new Column(
    children: <Widget>[
      Container(
        child: Text(title),
      ),
      Container(
        child: Text(description),
      ),
    ],
  );
}

数据: 对象列表

List<AboutUsData> data = [
    new AboutUsData(
      title: 'Our Vision',
      description:
          'OUR VISION',
    ),
    new AboutUsData(
      title: 'Our Mission',
      description:
          'OUR MISSION',
    ),
    new AboutUsData(
      title: 'Our Values',
      description:
          'As we grow as a company',
    ),
  ];

我怎样才能从那个.map文件中获取索引? - Dani
1
现在,您可以通过某个变量手动计算迭代次数,比如说 count。设置 count = 0,然后根据每次迭代添加 count+=1 - WasiF

9

由于之前的回答对我来说不够满意,所以我找到了另一种解决方案。

Flutter提供了在图形界面上一行内编写条件语句的可能性,因此您可以在单行中插入循环语句,然后再插入其他不同的小部件。这是对主要问题的一个实用示例:

 Column(
    children: <Widget>
      [
        for (int i = 0;
        i < workouts.series.length;
        i++)
          "//CREATE N YOUR WIDGETS//",
          new Text(
          "${workouts.series.length} x ${exerciseWorkout.repsToDo} ",
          style: TextStyle(
          color: Colors.black87,
          fontSize: 16,
          fontWeight: FontWeight.bold),
          )
      ],
     )

1
我测试了一下。只有第一个小部件会被循环迭代。其他的只是在之后添加。 - Alexufo

2

我有同样的问题,我有一个列表:

List<Info> li = [
    Info(name: "oussama", height: 180, date: DateTime.now()),
    Info(name: "mehdy", height: 150, date: DateTime.utc(1997, 05, 14)),
    Info(name: "ahmed", height: 190, date: DateTime.utc(1997, 04, 11)),
    Info(name: "sofiene", height: 160, date: DateTime.utc(1995, 07, 13)),
    Info(name: "mohamed", height: 150, date: DateTime.utc(1994, 01, 17))
];

我希望它以列的形式显示它们,返回一个list<Widget>,所以我按照@Günter Zöchbauer所说的做法创建了一个getList()函数:

List<Widget> getList() {
    List<Widget> childs = li
        .map((e) => Row(children: <Widget>[
              Text(e.name, style: const TextStyle(fontSize: 25)),
              Text("${e.height}", style: const TextStyle(fontSize: 25)),
              Text("${e.date}", style: const TextStyle(fontSize: 25))
            ]))
        .toList();
    return childs;
  }

然后我将其赋值给Column

body: Container(
 child: Column(
   children: getList()
))

它对我有效 :)


0

为解决此错误

The element type 'T' can't be assigned to the list type 'Object'.dartlist_element_type_not_assignable

您可以在Equatable包中使用此代码: @override List<Object?> get props => [value];


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接