Flutter: Array of TextEditingController

Viewed 10651

What is the best way to set an array of TextEditingController in a flutter . I mean I need to get a value array of Textfield(1 to n) value and sent to the server.

Can anyone help how to achieve this?

I tried

for(int i=1;i<75;i++) { 
TextEditingController _controller[i] = TextEditingController(); 
}

Regards, Sathish

3 Answers

There are plenty of ways to do that

List<TextEditingController> _controller = List.generate(74, (i) => TextEditingController());

or

List<TextEditingController> _controller = [];
for (int i = 1; i < 75; i++) _controller.add(TextEditingController());

or

List<TextEditingController> _controller = [
  for (int i = 1; i < 75; i++)
    TextEditingController()
];

You have to add a list of TextEditingController and need to add the contoller text to that list and parse it as you need.

  List<String> selection = [];  
 List<Product> productList = []; 

 //---------Adding contoller to list   
  
 productProvider.getAll(user.guid).forEach((element) {//---List<Product>
 final TextEditingController quantityController = 
 TextEditingController(text: element.quantity);
 quantityControllers.add(quantityController);
 });

   //-------Adding list of products to list
  List<Map<String, dynamic>> productItems = [];
   List<Product> productOriginalList = 
   productProvider.getAll(user.guid);
   for (int i = 0; i < productOriginalList.length; i++) {
   final Product product = productOriginalList[i];
   if (selection.contains(product.equipmentId)) {
               
   productItems.add(product.toJson(quantityControllers[i].text));
              }

 /* Map<String, dynamic> toJson(String quan) => {
'ProductId': id,
'Quantity': quan,
 };     
TextField(
controller: quantityControllers[index],*/

If you are using a dynamic widgets you can use -

TextEditingController _controller = new  TextEditingController(); 

inside your dynamic widget.This will automatically create new textediting controller evertime your widget runs. and at last you can store that value in your list.

Example :-

List <String>controllers = [];
controllers.add(_controller.text.toString)
Related