Search code examples
flutterdartcalculator

How do I make TextField's text change on key presses?


I'm trying to make a calculator app on Android Studio using Flutter.

How can I have a TextField (or any other widget) that can be used to input numbers either by the phone's keyboard or by clicking on the numbers pad provided in my app (calculator)?

And when the user presses an operation button (+ , - , * , /) how can I put the current text in the TextField in a variable and then empty the Field to be able to type more numbers?


Solution

  • I assume you are creating a calculator with a display, where it is possible to type with the keyboard or press buttons that add the operations or numbers to the display.

    Assign a TextEditingController to the TextField of the Display

    final displayController = TextEditingController();
    
    TextField(
        controller: displayController 
        ...
    ),
    

    The operation buttons need simple to trigger on tap:

    setState(() {
        displayController.text += ' + '; // assuming add operation
    });
    

    Instead, to evaluate the final expression on the display, I suggest looking into premade libraries like math_expressions