A.A
A.A

Reputation: 4091

Dart define generic function

I used the following code to define a function type

typedef DownloadCallback = Future<StreamedResponse> Function<T>(
  BuildContext context,
  T fileIdentifier,
);

And created a function that is similar to the type

Future<StreamedResponse> publicFileDownloader(
  BuildContext context,
  String url,
) {
  final request = Request('GET', Uri.parse(url));
  return Client().send(request);
}

But I have the following error

The argument type 'Future Function(BuildContext, String)' can't be assigned to the parameter type 'Future Function(BuildContext, T)'.

How can I fix the error without using dynamic type?

Upvotes: 0

Views: 30

Answers (1)

julemand101
julemand101

Reputation: 31209

This is another case where trying to specify a type ends up making Dart more confused. The problem is that the following:

final DownloadCallback downloader = publicFileDownloader;

Actually means:

final DownloadCallback<dynamic> downloader = publicFileDownloader;

Therefore, what you should do is the following:

final DownloadCallback<String> downloader = publicFileDownloader;

Next problem is wrong use of generic when you are declaring your typedef. What you actually want are properly the following:

typedef DownloadCallback<T> = Future<StreamedResponse> Function(
  BuildContext context,
  T fileIdentifier,
);

So the complete code would be:

typedef DownloadCallback<T> = Future<StreamedResponse> Function(
  BuildContext context,
  T fileIdentifier,
);

Future<StreamedResponse> publicFileDownloader(
  BuildContext context,
  String url,
) {
  final request = Request('GET', Uri.parse(url));
  return Client().send(request);
}

final DownloadCallback<String> downloader = publicFileDownloader;

Upvotes: 1

Related Questions