Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating widgets based on a list

Tags:

flutter

dart

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.

like image 479
Dhiraj Sharma Avatar asked Jun 18 '18 06:06

Dhiraj Sharma


1 Answers

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

enter image description here Full Example

like image 194
Raouf Rahiche Avatar answered Oct 18 '22 23:10

Raouf Rahiche