使用两个嵌套循环创建一个 Flutter 小部件

Creating a Flutter widget with two nested loops

我想在 Flutter 中创建一个小部件,如下所示:

文本字段组 1

[第一个文本字段]

[第二个文本字段]

文本字段组 2

[第一个文本字段]

[第二个文本字段]

我的代码如下所示:

class LoopWidget extends StatelessWidget {
  List textFieldLabels = ['The first text field', 'the second text field'];
    @override
    LoopWidget();
  Widget build(BuildContext context) {
    return Column(children: [
        for(i = 0; i < 2; i++)
         for(j = 0; j < 2; j++)
    //The title should be here
         (j == 0) ? Text('Text field group ' + (i+1).toString()),
         Container(child: 
        TextField(
                    decoration: InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: textFieldLabels[j],
                  )))]
    );
  }
}

但是,这不起作用。三元运算符是执行此操作的正确方法吗?如果不是会是什么?

试试这个

class LoopWidget extends StatelessWidget {
  @override
  LoopWidget();
  final List textFieldLabels = [
    'The first text field',
    'the second text field'
  ];
  Widget build(BuildContext context) {
    return Column(
      children: [
        for (int i = 0; i < textFieldLabels.length; i++) ...[
          Text('Text field group ${i+1}'),
          for(String labelText in textFieldLabels)
            TextField(
            decoration: InputDecoration(
              border: OutlineInputBorder(),
              labelText: labelText,
            ),
          ),
         
        ],
      ],
    );
  }
}

我结合使用了for loopfor-in loop

您的代码已修改:

class LoopWidget extends StatelessWidget {
  @override
  LoopWidget();
  int i;
  int j;
  Widget build(BuildContext context) {
    return ListView(
      children: listOfWidgets(),
    );
  }
  List textFieldLabels = ['The first text field', 'the second text field'];
  List<Widget> listOfWidgets() {
    List<Widget> list = new List();
    for (i = 0; i < 2; i++) {
      for (j = 0; j < 2; j++) {
        if (j == 0) {
          list.add(
            new Text('Text field group ' + (i + 1).toString()),
          );
        }
        list.add(
          new Container(
            child: TextField(
              decoration: InputDecoration(
                border: OutlineInputBorder(),
                labelText: textFieldLabels[j],
              ),
            ),
          ),
        );
      }
    }
  }
}