Creating widgets based on a list

2019-08-06 20:07发布

问题:

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.

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.

回答1:

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

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

Full Example



标签: dart flutter