我正在为我的项目实施 Web 令牌,我想在我提出请求后执行检查以查看是否需要更新我的令牌。下面是一个示例请求:
Future getMessages() async => await http.get(Uri.parse(url), headers: headers);
我有一个函数尝试请求(请求)
Future attemptRequest(request) async {
final response = await request();
...
}
我想传入 http.get(etc) 以便我可以运行类似的东西
Future getMessages() async => await attemptRequest(http.get(Uri.parse(url), headers: headers));
参数的数据类型应该是什么?因为当我让它保持动态时
attemptRequest(http.get(params));
我收到以下错误
Error: NoSuchMethodError: 'call'
Dynamic call of object has no instance method 'call'.
Receiver: Instance of '_Future<Response>'
我总是可以让 http.get 像一个 lambda
attemptRequest(() => http.get())
但我不能等待它。我能做些什么?
首先要注意的是你可以制作你的 lambda async
; 请参见下面的示例 2。(找出类型应该是什么的一个快速提示是查看 Dart 分析的输出。您可以将类型设置为Function
,分析器会告诉您Function
无法分配,Future<http.Response> Function(Uri, {Map<String, String>? headers})
所以现在您知道函数的 typedef必须。)
在版本 1 中,我们传入函数及其参数。
在版本 2 中,我们传入一个 lambda。
import 'package:http/http.dart' as http;
void main() async {
final url = 'https://www.pub.dev';
final headers = <String, String>{};
await attemptRequest1(Uri.parse(url), http.get, headers: headers);
await attemptRequest2(() async => http.get(Uri.parse(url), headers: headers));
}
Future<http.Response> attemptRequest1(
Uri uri,
Future<http.Response> Function(Uri, {Map<String, String>? headers})
requestFunction1,
{Map<String, String>? headers}) async {
return await requestFunction1(uri, headers: headers);
}
Future<http.Response> attemptRequest2(
Future<http.Response> Function() requestFunction2,
{Map<String, String>? headers}) async {
return await requestFunction2();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句