Reputation: 87
I want to create multi input in list view with dynamic total item count . I use list of textcontroller but when I input a data all controller show with same value.
this my controller :
int totalItem = 15;
List<TextEditingController> _color = List.filled(15, TextEditingController());
List<TextEditingController> _brand = List.filled(15, TextEditingController());
implement at textfield :
Padding(
padding: const EdgeInsets.only(bottom: 10, left: 20, right: 20),
child: TextFormField(
controller: _color[index],
decoration: InputDecoration(
hintText: "Color",
labelText: "Color",
),
),
),
Padding(
padding: const EdgeInsets.only(bottom: 10, left: 20, right: 20),
child: TextFormField(
controller: _brand[index],
decoration: InputDecoration(
hintText: "Brand",
labelText: "Brand",
),
),
),
When run the app text controller show with same value. Please help me to solve this problem?
Complete code : https://github.com/gunartha/listview_with_multi_input
Thank you.
Upvotes: 2
Views: 3637
Reputation: 3001
I think this happens because of the way the List.filled
constructor works. In the documentation it mentions:
Creates a list of the given length with
fill
at each position.
Implying that fill
(in this case your TextEditingController
) is only initialized once, and a reference to this same controller is then put in each index. As a result, all color fields are controlled by (a reference to) the same Controller instance, and the same goes for brands.
To resolve this, you'll need to use a different way to initialize your list of controllers. A simple loop would suffice, but you may also be able to come up with a more elegant solution.
Here's some example code to initialize the lists in a loop in initState
:
List<TextEditingController> _color = [];
List<TextEditingController> _brand = [];
@override
void initState() {
for (int i = 0; i < totalItem; i++) {
_color.add(TextEditingController());
_brand.add(TextEditingController());
}
super.initState();
}
Which works as expected on my machine.
Upvotes: 1