Home > Software design >  List of string is getting duplicated
List of string is getting duplicated

Time:11-24

I am generating text fields dynamically and I am trying to get the contents of the text fields.

//I declared a list of string and generated it using the length of my product.
late final List<String> recovered; 

//the length of the products is 3
recovered = List.generate(products.length, (index) => "")); 

TextField(
   onSubmitted: (value) {
      recovered.insert(index, value);
      log("the value is $value");
      setState(() {});
   },    
   controller: myControllers[index],
   decoration: const InputDecoration(
       enabledBorder:OutlineInputBorder(
             borderSide: BorderSide(
                  width: 1,
                  color: Colors.grey)),

     ),
),

I inserted 1,2,4 into the textFields generated by my listView Builder and got the following values [1, 2, 4, , , ] instead of [1, 2, 4].

CodePudding user response:

Calling insert adds them to the list. I believe you want to replace them. For that, instead of

recovered.insert(index, value);

you need to do

recovered[index] = value;

CodePudding user response:

on your Submit you need to check if the value is empty or not then add it to your list:

onSubmitted: (value) {
    if(value.isNotEmpty){
      recovered.insert(index, value);
      log("the value is $value");
      setState(() {});
    }
      
},
  • Related