创建一个带有两个嵌套循环的Flutter小部件



我想在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],
),
),
),
);
}
}
}
}

最新更新