Creating widgets based on a list

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


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

Tags:

Dart

Flutter