AzReddy
AzReddy

Reputation: 23

I am trying to create list of TextFormFields which takes numbers as inputs and I want to Sum all those numbers

I am trying to create list of TextFormFields which takes numbers as inputs and I want to Sum all those numbers. When I click on a button on app bar new textformfield appears and user enters value..validator is also working fine...But I am not able to do the Sum. When I used print in Onsaved method it displays all the entered values..If I use Controller, whatever the text we enter in formfield it is displaying same same in all the other textfields also..so controller is not working...I created TextFormField in different function and calling that function when button is pressed. I created another button to go to next screen at the same time to validate which works fine... Below is the TextFormField code: Please help to Sum all the values entered in it:

      child: TextFormField(
        // controller: _childController,
        decoration: InputDecoration(
            hintText: 'Value $_count',
            border: InputBorder.none,
            contentPadding: EdgeInsets.only(top: 5, left: 20)),
        keyboardType: TextInputType.number,
        style: TextStyle(
          color: Color.fromARGB(255, 0, 0, 0),
          fontWeight: FontWeight.w400,
          fontSize: 24,
        ),
        validator: (String value) {
          double sal = double.tryParse(value);
          if (sal == null) {
            return 'enter or delete row';
          }
        },
        onSaved: (String value) {
          // print(_childController.text);
          // print(value);              
          _mVal = value;
          double _mVal2 = double.tryParse(_mVal);              
          double _mVal3;
          
          print(_mVal);
          int k = 0;
          _children.forEach((element) {
           
            
            int y = int.tryParse(_mVal);
            k=k+y;
            print(k);
          }
          

Upvotes: 1

Views: 1159

Answers (1)

Lulupointu
Lulupointu

Reputation: 3584

Here is a quick example of how you can achieve this:

import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      home: Test(),
    ),
  );
}

class Test extends StatefulWidget {
  @override
  _TestState createState() => _TestState();
}

class _TestState extends State<Test> {
  final _formKey = GlobalKey<FormState>();
  List<TextEditingController> textFieldControllers = [];
  int numberOfTextFields = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          addNewTextField();
        },
      ),
      body: Stack(
        children: [
          Form(
            key: _formKey,
            child: ListView.builder(
              itemCount: numberOfTextFields,
              itemBuilder: (BuildContext context, int index) {
                return TextFormField(
                  validator: (String value) {
                    double sal = double.tryParse(value);
                    if (sal == null) {
                      return 'enter or delete row';
                    }
                    return null;
                  },
                  controller: textFieldControllers[index],
                );
              },
            ),
          ),
          Align(
            alignment: Alignment.bottomCenter,
            child: TextButton(
              onPressed: () {
                if (_formKey.currentState.validate()) {
                  showDialog(
                      context: context,
                      builder: (BuildContext context) {
                        return Center(
                          child: Material(
                            child: Container(
                              padding: EdgeInsets.all(10.0),
                              child: Text(
                                  'The sum is ${textFieldControllers.fold(0, (previousValue, element) => previousValue + int.parse(element.value.text))}'),
                            ),
                          ),
                        );
                      });
                }
              },
              child: Container(
                padding: EdgeInsets.all(10.0),
                color: Colors.redAccent,
                child: Text('Tap to sum'),
              ),
            ),
          ),
        ],
      ),
    );
  }

  void addNewTextField() {
    textFieldControllers.add(TextEditingController());
    numberOfTextFields++;
    setState(() {});
  }

  @override
  void dispose() {
    textFieldControllers.forEach((textFieldController) => textFieldController.dispose());
    super.dispose();
  }
}

You can expand on this idea to remove textField if needed. Just don't forget to dispose your textFields.

How does this work: Each time a TextField Widget is create, an associated TextEditingController is created and given to the TextField. When we want to sum, we just iterate on the TextEditingController list.

Upvotes: 1

Related Questions