基于列表创建窗口小部件

时间:2018-06-18 06:26:47

标签: dart flutter

我有一个参数n,我必须创建n个文本字段并听取它们,并捕获所有这些字段的值。 说我必须对它们进行计算。我该如何实现这一目标?我试图将循环与小部件组合,但是我遇到了很多错误。

当我使用单独的函数返回列的子属性的小部件列表时,会抛出一个错误,指出type int is not a subtype of type string of source

3 个答案:

答案 0 :(得分:1)

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;
}

然后在窗口小部件的children属性中使用此函数,例如列窗口小部件

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(); 
        } ,
      ),
    );
  }
} 

enter image description here Full Example

答案 1 :(得分:0)

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'),
              ),
            );
        },
      ),
    );

答案 2 :(得分:0)

从列表创建 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);
 
  }

看起来像这样:

screenshot