0

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?

Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
Zee
  • 7
  • 4
  • 1
    Hey, Actually it's depend on the app and your experience level with flutter. Because if you have just started with flutter then its good and when you will get experience then you will improve this code in better way on you own. – Rohan Jariwala Oct 05 '22 at 16:22
  • Hi @RohanJariwala , thank you for your reply, could you recheck the question? i'm trying to make the results works as double so the result can come with decimal points. thanks – Zee Oct 05 '22 at 16:49
  • Does parsing the input as double help you? double.parse(num1controller.text) – Danny Rufus Oct 05 '22 at 16:57

1 Answers1

0

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);
});   
Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56