4
final ValueSetter<int> setVal; 

can be assigned a function callback that accepts one parameter like

setVal=(i){
     //assign i to some variable
            }

What if I wanted the callback to accept 2 parameters like

  setVal=(i,j){
         //assign i and j to some variable
                }

?

5 Answers 5

5

Variables of type Function can be declared as follows:

void main() {
  void Function(int) setVal1;
  void Function(int, int) setVal2;

  setVal1 = (int i) => print('$i');
  setVal2 = (int i, int j) => print('$i, $j');
  final String Function(int, int, [double]) setVal3 =
      (int i, int j, [double k]) => '$i, $j, $k';

  final i = 0;
  final j = 1;
  final double k = 2.0;
  setVal1(i);
  setVal2(i, j);
  print(setVal3(i, j));
  print(setVal3(i, j, k));
}
Sign up to request clarification or add additional context in comments.

3 Comments

Okay so how do I make the second parameter optional?
@MichelThomas you accepted this answer even it does not answer your question?
@MichelThomas Ha-ha. This was an example of How to declare a function callback(s) that accepts multiple parameters in Dart/Flutter. Including an additional answer to the question asked in the comments about how to make the second parameter optional. Yeah...
4

ValueSetter is typedef'ed as:

typedef ValueSetter<T> = void Function(T value);

As in, a function that takes one parameter. So, no, you can't hand it a function that takes two parameters.

Comments

2
final Function(int, String) = (int a, String b){
  /* do stuff */
}

Comments

1

Just put whatevery you want in a map and pass the map. Something like this:

  Map<String, dynamic> updateMap = {
    'id': id,
    'value': value


  widget.onUpdate(updateMap);

Comments

0

You can declare your own type, just add this def in your helpers.dart file:

typedef ValueSetter2<T, E> = void Function(T value, E value2);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.