user13427040
user13427040

Reputation:

How to unstringify(convert into a non string) a string in dart?

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?

Upvotes: 1

Views: 233

Answers (2)

julemand101
julemand101

Reputation: 31199

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.

Upvotes: 1

Lesiak
Lesiak

Reputation: 25936

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.

Upvotes: 0

Related Questions