Search code examples
flutterdartoperators

How to save operators in Dart


I want to do something like this in dart.

var z = +

and then put it in another var like this

var x = 5 z 5

And when I did this

var z = +

I get an Error

Expected an identifier.


Solution

  • you can not make variable operators in dart though what you can do is to create a custom variable for the same by doing:

    void main() {
    var operators = {
        '+': (a, b) { return a + b; },
        '<': (a, b) { return a < b; },
         // ...
    };
    
    var op = '+';
    var x = operators[op]!(10, 20);
      print(x);
    }