Home > other >  Can a Map in Dart contains functions?
Can a Map in Dart contains functions?

Time:10-17

I've tried to make a Map that contains functions. And when I tried to run it, it returned error :

The method "mltply" isn't defined for the type Map.

Map<String, Function> library = {
    "mltply": (int x, int y) => x * y,
    "addtn": (int x, int y) => x   y
  };
  print(library.mltply(2, 4));

CodePudding user response:

Yes.

Your code is wrong, try this:

Map<String, Function> library = {
    "mltply": (int x, int y) => x * y,
    "addtn": (int x, int y) => x   y
  };
  print(library["mltply"]!(2, 4));

Notice, maps need to be accessed via brackets and a string (unlike Javascript).

Furthermore, you should give your functions explicit function definitions when possible.

Instead of Function use int Function(int, int)

  • Related