Rostyk
Rostyk

Reputation: 1159

How to get textfields data in flutter

I have a Textfield which has a controller so I can grab data from it.
But how can I do it when I create an input by a button click, for example, I created 10 text fields how can I get data from them?

Thanks for your answers but you did not understand me, I can't just create controllers manually, I have a button once I clicked upon it a new textfield is created, I can click on it as many times as I want it can be 100 times for example, because of this I need to do it programmatically if it is possible.

Thanks

Upvotes: 0

Views: 252

Answers (3)

Tanner Davis
Tanner Davis

Reputation: 114

Edit: added lines about accessing the text inside each controller

You could try keeping a List of TextEditingControllers.

When the button is pushed you will add a new TextEditingController to the List and then create the new TextField that the controller will be connected to.

Then to get the contents of each controller just iterate through the List and access the text member of the controller.

Just remember you will have to go through that List in your widget's dispose method and call their dispose methods as well.

final List<TextEditingController> _controllers = []

void onButtonPress() {
  TextEditingController newController = TextEditingController()
  _controllers.push(newController)
  // Make new TextField and use the new controller in it
  // Then figure out how to add the new TextField to your state (probably using setState)
}

Upvotes: 1

M.Ali
M.Ali

Reputation: 10235

final controllerOne= TextEditingController();
final controllerTwo= TextEditingController();


TextFiledOne(
controller: controllerOne,
....
);

TextFiledTwo(
controller: controllerTwo,
....
);


onPressed(){
 String dataOne = controllerOne.text;
 String dataTwo = controllerTwo.text;
....
}

Upvotes: 0

kaarimtareek
kaarimtareek

Reputation: 496

in on pressed method :

(){
    //this will get the last input that user entered in the textfield
   String data = _myController.text;

    if(data.isEmpty) 
      //do something 
      }

Upvotes: 0

Related Questions