int numberOfTextFields = 1;
List<TextEditingController> textFieldControllers = [];
final _numsFormKey = GlobalKey<FormState>();
Form(
key: _numsFormKey,
child: ListView.builder(
shrinkWrap: true,
itemCount: numberOfTextFields,
itemBuilder: (BuildContext? context, int? index) {
int i = index! 1;
return Row(
children: [
Container(
height: 52,
width: 140,
margin: EdgeInsets.only(left: 20.0, bottom: 10),
child: TextFormField(
keyboardType: TextInputType.number,
// controller: textFieldControllers[index], //getting range error if i use this
decoration: InputDecoration(
hintText: 'Enter Number $i',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.0),
),
),
style: TextStyle(
color: Color.fromARGB(255, 0, 0, 0),
fontWeight: FontWeight.w400,
fontSize: 24,
),
validator: (value) {
if (value!.isEmpty) {
return "Enter or delete";
} else if (value.length > 12) {
return "Enter < 12 digits";
}
return null;
},
onSaved: (value) {}
in the IconButton onpressed used below:
onPressed: () {
print("number of boxes=$numberOfTextFields");
textFieldControllers
.add(TextEditingController());
numberOfTextFields ;
setState(() {
});
}),
There is a Save Button, on clicking it:
_validateNums() async {
if (_numsFormKey.currentState != null &&
_numsFormKey.currentState!.validate()) {
_numsFormKey.currentState!.save();
} else {
}
}
And when I just print(value) or print(int.parse(value)) in the OnSaved{} it is printing all the values I entered.
double totalsum = (textFieldControllers.fold(0,(previousValue, element) {return previousValue
double.tryParse(element.value.text)!; double.parse(element.value.text);
I am not able to use the above because I am getting range error while using controller in TextFormField.
How do I get the sum of all those values on clicking Save button. I tried using for loop but it did not work
CodePudding user response:
int numberOfTextFields = 1;
List<TextEditingController> textFieldControllers = [];
you declared you had 1 textfield, but at the beginning you have 0, you will always say you have more textfields that you do, that is why you get a range error.
Also, textFieldControllers
is a list, which means it has a length method that keeps track of the number of items for you:
print("number of boxes=${textFieldControllers.length}");
...
itemCount: textFieldControllers.length,
itemBuilder: (BuildContext? context, int? index) {
...