skip to Main Content

How do i test a expression in a string and evaluate it:

String expression = "'Cat' != 'Dog'";

I want that something like that:

if(expression) // return it logic result

like this:

if('Dog' != 'Doc'){
   return true;
}else{
   return false;
}

That in flutter, thanks in advance.

2

Answers


  1. Chosen as BEST ANSWER

    I had to create my own function that resolve my problem:

    dynamic evaluateExpression(String expression) {
      // Remove white spaces from the expression
      expression = expression.replaceAll(' ', '');
    
      // Parse the expression
      dynamic evaluate(String expr) {
        if (expr == 'true') return true;
        if (expr == 'false') return false;
        if (RegExp(r'^d+$').hasMatch(expr)) return int.parse(expr);
        if (RegExp(r'^[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)$').hasMatch(expr)) {
          return double.parse(expr);
        }
        return expr; // Assume it's a string
      }
    
      // Evaluate the expression recursively
      dynamic evaluateHelper(String expr) {
        // Handle string comparisons separately
        if (expr.contains('==')) {
          final parts = expr.split('==');
          return evaluate(parts[0]) == evaluate(parts[1]);
        } else if (expr.contains('!=')) {
          final parts = expr.split('!=');
          return evaluate(parts[0]) != evaluate(parts[1]);
        } else if (expr.contains('<=')) {
          final parts = expr.split('<=');
          return evaluate(parts[0]).compareTo(evaluate(parts[1])) <= 0;
        } else if (expr.contains('>=')) {
          final parts = expr.split('>=');
          return evaluate(parts[0]).compareTo(evaluate(parts[1])) >= 0;
        } else if (expr.contains('<')) {
          final parts = expr.split('<');
          return evaluate(parts[0]).compareTo(evaluate(parts[1])) < 0;
        } else if (expr.contains('>')) {
          final parts = expr.split('>');
          return evaluate(parts[0]).compareTo(evaluate(parts[1])) > 0;
        }
    
        // No comparison operators found, return null
        return null;
      }
    
      // Evaluate the expression
      return evaluateHelper(expression);
    }
    

    I hope it helps someone.


  2. as @Vilsad PP mentioned in the comment we can use dart_eval package for this kind of things

    import 'package:dart_eval/dart_eval.dart';
    
    void main() {
      var data = eval("'dog' != 'cat'");
      print(data); //true
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search