我有一个参数n,需要创建n个文本框并监听它们,以获取所有这些字段的值,然后进行计算。我该如何实现这个功能?我尝试将循环与小部件组合在一起,但是我得到了许多错误。
当我使用单独的函数返回列子属性的小部件列表时,它会抛出一个错误,指出“类型int不是源代码字符串类型的子类型”。
d
参数生成一个列表,然后从该列表生成文本字段和文本编辑控制器的列表。createTexttextfields (int d){
var textEditingControllers = <TextEditingController>[];
var textFields = <TextField>[];
var list = new List<int>.generate(d, (i) =>i + 1 );
print(list);
list.forEach((i) {
var textEditingController = new TextEditingController(text: "test $i");
textEditingControllers.add(textEditingController);
return textFields.add(new TextField(controller: textEditingController));
});
return textFields;
}
然后在您的小部件的子属性中使用此函数,例如列部件
return new Scaffold(
appBar: new AppBar(),
body: new Column(
children: createTexttextfields(6),
),
);
但是如果你想访问它们,你不能通过一个函数来做,你必须将它们创建为变量。
Widget build(BuildContext context) {
var d=5;//the number of text fields
var textEditingControllers = <TextEditingController>[];
var textFields = <TextField>[];
var list = new List<int>.generate(d, (i) =>i + 1 );
list.forEach((i) {
var textEditingController = new TextEditingController(text: "test $i");
textEditingControllers.add(textEditingController);
return textFields.add(new TextField(controller: textEditingController));
});
return new Scaffold(
appBar: new AppBar(),
body: new Column(
children: textFields),
floatingActionButton: new FloatingActionButton(
onPressed: (){
//clear the text in the second TextEditingController
textEditingControllers[1].clear();
} ,
),
);
}
}
return Container(
height: 50,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: 60,
itemBuilder: (context, index){
return ButtonTheme(
minWidth: 20.0,
height: 20.0,
child: MaterialButton(
color:AppTheme.colorDark,
colorBrightness: Brightness.dark,
onPressed: () => print(index),
shape: RoundedRectangleBorder(borderRadius:
BorderRadius.circular(10.0)),
child: Text('$index'),
),
);
},
),
);
从List创建一个List<Widget>
的非常通用的示例:
Widget _buildColumn() {
var stringList = ["a", "b", "c"];
// Create a List<Text> (or List<MyWidget>) using each String from stringList
var textList = stringList.map<Text>((s) => Text(s)).toList();
// use that list however you want!
return Column(children: textList);
}