根据列表创建窗口小部件 [英] Creating widgets based on a list
问题描述
我有一个参数n,并且我必须创建n个文本字段并收听它们,并捕获所有这些字段的值。
说我必须对它们执行计算。我该如何实现?我试图将循环与小部件结合在一起,但是却遇到很多错误。
I have a parameter n, and i have to create n textfields and listen to them, and capture the value of all these fields. Say I have to perform calculations on them. How do I achieve this? I tried to combine loops with widgets but I get lots of errors.
当我使用一个单独的函数返回该列的children属性的窗口小部件列表时,它抛出错误,指出 type int不是的子类型。输入源字符串
。
When I used a separate function to return a list of widgets for column's children property, it throws an error stating type int is not a subtype of type string of source
.
推荐答案
从您的 d
参数生成一个列表,然后生成一个列表列表中的文本字段和文本编辑控制器
generate a list from your d
parameter and then generate a list of text field and text editing contotlers from that list
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;
}
,然后在小部件的children属性中使用此功能,例如列小部件
and then use this function in the children property of your widget for example the column widget
return new Scaffold(
appBar: new AppBar(),
body: new Column(
children: createTexttextfields(6),
),
);
但是,如果要访问它们,则不能通过函数来执行此操作,必须将它们创建为变量
But if you want to access them you can't do that by a function you must create them as variables
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();
} ,
),
);
}
}
这篇关于根据列表创建窗口小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!