首页 > 解决方案 > 是否可以使用 for 循环在 build 方法中创建小部件?

问题描述

我想制作一个不可滚动的网格,它的整体扩展到它的父级。我正在尝试在构建方法中运行一个 for 循环来创建行和列。但我收到以下错误

The element type 'Set<Row>' can't be assigned to the list type 'Widget'.

The element type 'Set<Text>' can't be assigned to the list type 'Widget'.

从 for 循环。为什么是这样?我该如何解决这个问题?

import 'package:flutter/material.dart';

class ExpandingGridArguments{
  List<Widget> tiles;
  int columns;
  int rows;
  ExpandingGridArguments(List<Widget> tiles, int columns)
  {
    this.tiles = tiles;
    this.columns = columns;
    this.rows = (tiles.length / columns).ceil();
  }
}

class StaticGrid extends StatelessWidget {

  @override
  Widget build(BuildContext context) {

    final ExpandingGridArguments arguments = ModalRoute.of(context).settings.arguments;

    return Column(
      children: 
      [
        for(int c = 0; c < arguments.rows; c++ )
        {
          Row
          (
            children : 
            [
              for(int r = 0; r < arguments.columns; r++)
              {
                Text('A row'),
              }
            ]
          ),
        }
      ]
    );
  }
}

标签: flutter

解决方案


内部列表的语法与for您所做的略有不同。

代替:

[
  for (var i = 0; i < 42; i++) {
    Text('$i')
  }
]

它没有使用{}

[
  for (var i = 0; i < 42; i++)
    Text('$i')
]

这样做的原因{}也用于创建Set/ Map

Set<int> hashSet = {};

因此,{}不支持使用内部列表来提高可读性,因为 Dart 会将“块”与创建Set


推荐阅读