Calculate from one TextField in flutter

Issue

I’m creating a flutter page that has one text field, user should put a number in this field and the page calculate his input with another int that i already added in the code.

i did it in a bad way as you can see below

first under the screen class i did

  TextEditingController num1controller = TextEditingController();
  int calculation = 10;
  String result = '0';

then I created a text field

CustomTextField(
                  controller: num1controller,
                  showCancelIcon: true,
                  autocorrect: false,
                  enableSuggestions: false,
                  keyboardType: TextInputType.number,
                  decoration: InputDecoration(
                    labelText: 'Label Text',
                    hintText: 'Hint Text',
                  ),
                ),

then i did the calculation as follows using an ElevatedButton

ElevatedButton(
                child: const Text('Calculate'),
                onPressed: () {
                  setState(() {
                    int sum = int.parse(num1controller.text);
                    var sum1 = sum ~/ calculation;
                    result = sum1.toString();
                  });
                },
              ),

Then i showed the results as follows:

 Text('$result')

Is it correct the way i did it? or should it be done in a better way? also How i can make result accepts decimal points? currently the result is not showing any decimal points?

Solution

You are doing integer division by adding ~ on sum ~/ calculation. It is also better using .tryPerse. If you like to accept double from TextFiled use double sum.

Instead of .toString(), you can use toStringAsFixed(2) on to show decimal point number.

I will prefer like

setState(() {
  double sum = double.tryParse(num1controller.text)??1;
  final sum1 = sum / calculation;
  result = sum1.toStringAsFixed(2);
});   

Answered By – Yeasin Sheikh

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *