Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
76 views
in Technique[技术] by (71.8m points)

How to pass a function onto a generic function parameter in Flutter?

For example, I have this function parameter:

class MyClass {

  U Function<T, U>(T data) callback;
  MyClass ({ this.callback }) : super();

}

var int Function(String value) func = (String value) => int.parse(value);
MyClass(callback: func); // error

The error is:

The argument type 'int Function(String)' can't be assigned to the parameter type 'U Function<T, U>(T)'.

How can I make this work?

EDIT:

Based on Shubhamhackz's answer, I conclude that the only thing wrong with my code is that because the generics are on the variables and not on the function parameters, and the variables are created when the class is declared and instantiated. I should put the <T, U> on the class declaration itself, and not on the function variable declaration. So the class declaration becomes like this:

class MyClass<T, U> {

  U Function(T data) callback;
  MyClass ({ this.callback }) : super();

}
question from:https://stackoverflow.com/questions/65896146/how-to-pass-a-function-onto-a-generic-function-parameter-in-flutter

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To declare a generic function parameter and pass it as argument. This is the way how I would implement it in dart.

typedef Callback<T,U> = U Function(T data);

void main() {
  Callback<String,int> func = (String value) {
    return int.parse(value);
  };
  MyClass(callback: func); 
}

class MyClass {

  Callback<String,int> callback;
  MyClass ({ this.callback }) : super() {
    print('MyClass Called');
  }
  
}

Output :

MyClass Called

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...