flutterdart

Math expression from a string in dart


This is the code I am using to separate a string into variables and operators. So that they can be operated upon.

String expression = "1567x356-234+908/56x12"; int lastPos = 0;

  List<double> exprVar = new List<double>();
  List<String> operator = new List<String>();

  for (int i =0; i < expression.length; i++) {

      if (expression[i] == "+" || expression[i] == "-" || expression[i] == "/" || expression[i] == "x") {

        operator.add(expression[i]);

        exprVar.add(double.parse(expression.substring(lastPos, i)));
        lastPos = i+1;
      }

    if (i == expression.length - 1) {
        exprVar.add(double.parse(expression.substring(lastPos, i+1)));
      }

  }

  print("The Numbers are is: $exprVar");
  print("The operators are: $operator");

I have two questions:

  1. Am I reinventing the wheel here? Is there a String library function in dart that I am unaware of that might make this code more convenient?

  2. Now that I have the numbers and operator, do I have to write code to determine the order of precedence of operators or can I make a giant single line expression and the processor would solve it for me?


Solution

  • use function_tree
    see documentation https://pub.dev/packages/function_tree#-installing-tab-

    final expressionsExample = [
       '2 + 2 - 2 - 2',
       '(3 + 2)^3',
       '3 * pi / 4',
       '3 * sin(5 * pi / 6)',
       'e^(-1)'
     ];
     for (final expression in expressionsExample) {
       print("'$expression' -> ${expression.interpret()}");
     }
    

    Output will be

    '2 + 2 - 2 - 2' -> 0
    '(3 + 2)^3' -> 125
    '3 * pi / 4' -> 2.356194490192345
    '3 * sin(5 * pi / 6)' -> 1.5000000000000009
    'e^(-1)' -> 0.36787944117144233