Passing TextEditingController as a paramater to a function?

3k Views Asked by At

I created Two text fields in flutter using a function, but I want to use two different TextEditingControllers for each. How can I pass a TextEditingController as a paramater to a function?

         Widget fieldmaker(String title) {
        return Container(
          width: double.infinity,
          height: 50,
          padding: EdgeInsets.symmetric(
            horizontal: 10,
          ),
          child: TextField(
            controller: ,
            decoration: InputDecoration(
              hintText: title,
              hintStyle: TextStyle(
                fontSize: 20,
              ),
              contentPadding: EdgeInsets.all(2),
            ),
          ),
        );
     }
final amountcontroller=TextEditingController();
  final titlecontroller=TextEditingController();

        Widget build(BuildContext context) {
      return Column(
        children: [
          fieldmaker('Title'),
          fieldmaker('Amount'),
        ],
      );
    }
3

There are 3 best solutions below

0
On BEST ANSWER

You can pass it as an argument to your function:

         Widget fieldmaker(String title,TextEditingController controller) {
        return Container(
          width: double.infinity,
          height: 50,
          padding: EdgeInsets.symmetric(
            horizontal: 10,
          ),
          child: TextField(
            controller: controller,
            decoration: InputDecoration(
              hintText: title,
              hintStyle: TextStyle(
                fontSize: 20,
              ),
              contentPadding: EdgeInsets.all(2),
            ),
          ),
        );
     }
final amountcontroller=TextEditingController();
  final titlecontroller=TextEditingController();

        Widget build(BuildContext context) {
      return Column(
        children: [
          //pass them to the function from here
          fieldmaker('Title',titlecontroller), 
          fieldmaker('Amount',amountcontroller),
        ],
      );
    }
0
On

If your fieldMaker method were a class FieldMaker extends StatefulWidget, the class could create the TextController and configure it based an the title. Then you can:

children: <Widget>[
  FieldMaker('Title'),
  FieldMaker('Amount'),
]
0
On

pass it like

fieldmaker('Title', amountcontroller);

and modify your function

fieldmaker(String title, TextEditingController yourTextEditingController){
//use yourTextEditingController here
return Container(
          width: double.infinity,
          height: 50,
          padding: EdgeInsets.symmetric(
            horizontal: 10,
          ),
          child: TextField(
            controller: yourTextEditingController,
            decoration: InputDecoration(
              hintText: title,
              hintStyle: TextStyle(
                fontSize: 20,
              ),
              contentPadding: EdgeInsets.all(2),
            ),
          ),
        );

}