skip to Main Content

for example, I want to write "5 + 3" in text field in flutter app, then press enter, after that, I want from application to convert the input to the result, I mean convert "5 + 3" to "8".

is there any way to do that in flutter?

thanks in advance for the help.

I searched about way in google, but did not find any thing.

2

Answers


  1. You can use this function to calculate your example field and improve it for your needs.

    int calculate(String textFieldInput) {
      List<String> inputList = textFieldInput.split(' ');
    
      int firstNumber = int.parse(inputList[0]);
      int secondNumber = int.parse(inputList[2]);
      String sign = '${inputList[1]}';
    
      int result = 0;
    
      if (sign == '+') {
        result = firstNumber + secondNumber;
      }
    
      return result;
    }
    
    Login or Signup to reply.
  2. You can make a TextField that calls an evaluation function when user submit the input, by having the evaluation inside the callback of onSubmitted. After that, set the TextField‘s controller text to the result of the evaluation. To evaluate the calculation from the input, you can use a package like math_parser.

    import 'package:math_parser/math_parser.dart';
    
    class SampleWidget extends StatefulWidget {
      const SampleWidget({super.key});
    
      @override
      State<SampleWidget> createState() => _SampleWidgetState();
    }
    
    class _SampleWidgetState extends State<SampleWidget> {
      final controller = TextEditingController();
    
      @override
      void dispose() {
        controller.dispose();
        super.dispose();
      }
    
      @override
      Widget build(BuildContext context) {
        return TextField(
          controller: controller,
          onSubmitted: (value) {
            final exp = MathNodeExpression.fromString(value);
            final result = exp.calc(MathVariableValues.none);
            controller.text = '$result';
          },
        );
      }
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search