Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast a variable as a function/method pointer in Dart? (Delegate?)

Say I have a Map type that stores functions/methods inside of it, like so:

Map triggerHandler = {
  'x' : (t) => hello(t)
};

Now, what I want to do next is to declare that the Type of these Map values are to be functions.

I can always do this:

Map<String, dynamic> triggerHandler = {
  'x' : (t) => hello(t)
};

But this doesn't help stop programmers from putting in non-functions into the Map values. 'x' could then be a String, or an Integer.

The reason I want to do this is because I have a function that needs to only accept Maps with functions as the values. Calling the array key of 'x' is done by triggerHandlerx when it is a function, rather than triggerHandler[x]. I haven't tested if this causes an error to occur or not, but this doesn't seem semantically correct to me.

It would seem that the most logical way to do this would be to set the Type for the value as a function. Such as giving a Map a type casted value of 'delegate':

Map<String, delegate> triggerHandler = { // Note, this won't work
  'x' : (t) => hello(t)
};

What is the correct way to do this in Dart? (If there is a way) Thank you.

like image 913
Will Squire Avatar asked Aug 02 '26 05:08

Will Squire


1 Answers

You can use Function as type or if you also want to specify the arguments and return type of these functions you can create typedefs.

Map<String, Function> triggerHandler = {
  'x' : (t) => hello(t)
};
typedef int SomeName(SomeType arg1);

Map<String, SomeName> triggerHandler = {
  'x' : (t) => hello(t)
};
like image 130
Günter Zöchbauer Avatar answered Aug 03 '26 23:08

Günter Zöchbauer