简体   繁体   中英

How to declare a function callback that accepts multiple parameters in Dart/Flutter?

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
                }

?

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.

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

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));
}

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM