过去,我使用返回Future<Response>. 我注意到我可以在.then()方法内返回其他类型,最终类型结果将根据我在 then 中返回的类型而改变。
但是当我更改为使用返回的包时,在其中返回Future<dynamic>不同的类型.then()不会再改变最终结果类型。它不断导致Future<dynamic>. 但我可以保证动态类型是一种Response类型。这是我尝试过的:
第一个:
Future<Response> get(String url) =>
fetcher.get(url).then((response) => response as Response); // error: Unhandled Exception: type 'Future<dynamic>' is not a subtype of type 'Future<Response>'
第二:
Future<Response> get(String url) =>
fetcher.get(url) as Future<Response>; // error: Unhandled Exception: type 'Future<dynamic>' is not a subtype of type 'Future<Response>'
第三:
Future<Response> get(String url) =>
fetcher.get(url).then((response) {
final result = response as Response;
return result;
}); // error: Unhandled Exception: type 'Future<dynamic>' is not a subtype of type 'Future<Response>'
在过去:
Future<List<Model>> get(String url) =>
client.get(url).then((response) => Model.fromJson(response.body)); // working.
我用于此的包:https ://pub.dev/packages/twitter_api#-example-tab-
编辑:澄清提取器:
import 'package:twitter_api/twitter_api.dart';
import "package:http/http.dart";
twitterApi fetcher = twitterApi(
consumerKey: consumerApiKey,
consumerSecret: consumerApiSecretKey,
token: locker.session?.token,
tokenSecret: locker.session?.secret
);
Future<Response> get(String path) {
final split = url.split("?");
final onlyPath = split[0];
final onlyParam = split.length > 1 ? split[1] : "";
final options = Map.fromIterable(onlyParam.split("&").where((it) => it.contains("=")), key: (e) => e.split("=")[0] as String, value: (e) => e.split("=")[1] as String);
return fetcher.getTwitterRequest("GET", onlyPath.replaceFirst("/", "", options: options).then((response) {
debugPrint ("GET ${response.request.url} Response: ${response.body}");
return response as Response;
});
}
输出:
[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type 'Future<dynamic>' is not a subtype of type 'Future<Response>'
#0 TwitterApiProvider.fetchUser (package:feazy/src/resources/twitter_api_provider.dart:11:70)
#1 Repository.fetchUser (package:feazy/src/resources/repository.dart:19:27)
#2 _HomeState.twitterLogin (package:feazy/src/ui/home.dart:50:21)
...
GET https://api.twitter.com/1.1/users/show.json?screen_name=somescreenname Response: {"id":<int>,"id_str":<string>,"name":"Some name","screen_name":"somescreenname",...
编辑2:进一步检查,我注意到在IDE上,IDE告诉我返回类型fetcher.getTwitterRequest()不是Future<dynamic>,而是dynamic。所以我像这样更改我的代码,但它仍然无法正常工作。
Future<Response> get (String path) {
...
final future = authClient.getTwitterRequest(...).then((response) {
debugPrint ("POST ${response.request.url} Response: ${response.body}");
return response as Response;
});
final futureResponse = future as Future<Response>;
return futureResponse;
}
在这种情况下,错误在 上final futureResponse = future as Future<Response>;,说的是同样的事情:Unhandled Exception: type 'Future<dynamic>' is not a subtype of type 'Future<Response>' in type cast。