FlutterLover
FlutterLover

Reputation: 671

How to calculate the total of two input field values in flutter?

I have two check boxes, the first one has this text age 22 the second one has age 32. I want to calculate the number part from the text: Example, 22 + 32. and I want to put the result in a text box. This is my example

Upvotes: 1

Views: 3783

Answers (1)

CopsOnRoad
CopsOnRoad

Reputation: 267464

Screenshot:

enter image description here

enter image description here

enter image description here

enter image description here

class _YourPageState extends State<YourPage> {
  int _age1 = 22, _age2 = 32, _totalAge = 0;
  bool _checkedAge1 = false, _checkedAge2 = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Padding(
        padding: const EdgeInsets.all(32.0),
        child: Column(
          children: <Widget>[
            CheckboxListTile(
              title: Text("Age ${_age1}"),
              value: _checkedAge1,
              onChanged: (age) {
                setState(() {
                  _checkedAge1 = age;
                  if (_checkedAge1) _totalAge += _age1;
                  else _totalAge -= _age1;
                });
              },
            ),
            CheckboxListTile(
              title: Text("Age ${_age2}"),
              value: _checkedAge2,
              onChanged: (age) {
                setState(() {
                  _checkedAge2 = age;
                  if (_checkedAge2) _totalAge += _age2;
                  else _totalAge -= _age2;
                });
              },
            ),
            Text("Total age = ${_totalAge}")
          ],
        ),
      ),
    );
  }
}

Upvotes: 3

Related Questions