Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
                }

?

like image 330
Michel Thomas Avatar asked Oct 12 '25 01:10

Michel Thomas


2 Answers

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));
}
like image 153
mezoni Avatar answered Oct 14 '25 14:10

mezoni


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.

like image 38
Randal Schwartz Avatar answered Oct 14 '25 15:10

Randal Schwartz