1

String x = '5 + 6'

How do I evaluate the string above so that it produces result. 5 + 6 equals 11. How do I get that result from the above string?

2
  • can you help me find that, any clue to the source I should look into? @julemand101 Commented Apr 30, 2020 at 13:31
  • I have added an answer with example of using two different packages. Commented Apr 30, 2020 at 13:43

2 Answers 2

1

Alternative you can also make use of the math_expressions package:

import 'package:math_expressions/math_expressions.dart';

void main() {
  String x = '5 + 6';
  print(solve(x)); // 11
}

int solve(String expr) =>
    (Parser().parse(expr).evaluate(EvaluationType.REAL, ContextModel()) as double)
        .toInt();

Or use expressions which seems to be more simple to use but have fewer features:

import 'package:expressions/expressions.dart';

void main() {
  String x = '5 + 6';
  print(solve(x)); // 11
}

int solve(String expr) =>
    const ExpressionEvaluator().eval(Expression.parse(expr), null) as int;

Both packages should work with Flutter.

Sign up to request clarification or add additional context in comments.

Comments

0
import 'dart:isolate';

void main() async {
  var sumString = '5 + 6';

  final uri = Uri.dataFromString(
    '''
    import "dart:isolate";

    void main(_, SendPort port) {
      port.send($sumString);
    }
    ''',
    mimeType: 'application/dart',
  );

  final port = ReceivePort();
  await Isolate.spawnUri(uri, [], port.sendPort);

  final int response = await port.first;
  print(response);
}

This is based on How do I execute Dynamically (like Eval) in Dart?

Also note:

Note that you can only do this in JIT mode, which means that the only place you might benefit from it is Dart VM command line apps / package:build scripts. It will not work in Flutter release builds.

2 Comments

is there any way to integrate it with flutter? Any packages, anything? @Lesiak
Check my answer: it will NOT work in flutter release build.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.