#flutter #dart
#трепещущий #дротик
Вопрос:
У меня есть этот код
import "./HTTPMethod.dart";
import '../../DataModel/DataModel.dart';
mixin RouterMixin {
HTTPMethod method;
String scheme;
String path;
String baseURL;
Map<String, dynamic> params;
Map<String, String> headers;
}
class Router with RouterMixin {
HTTPMethod method;
String scheme;
String path;
String baseURL;
Map<String, dynamic> params;
Map<String, String> headers;
Router._(this.method, this.path, this.scheme, this.baseURL, this.params,
this.headers);
// ignore: missing_return
static Router getRouter(method, path,
{scheme = "https://",
baseURL = "xyz.com",
params = const {},
headers = const {
"Accept": "application/json",
"Content-Type": "application/json"
}}) {
var headerValue = Map<String, dynamic>.from(headers);
DataModel.shared.authToken.then((value) {
print("TOKEN: $value");
if (value != null) {
headerValue["Authorization"] = value;
}
final router =
Router._(method, path, scheme, baseURL, params, headerValue);
return router;
}).catchError((error) {
print("ROUTER: ${error.toString()}");
});
}
}
Это выдает эту ошибку
flutter: type '_ImmutableMap<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic>'
Даже я пытался с простым
static Router routerValue(method, path,
{scheme = "https://",
baseURL = "zyx.com",
params = const {},
headers = const {
"Accept": "application/json",
"Content-Type": "application/json"
}}) {
Router router = Router._(method, path, scheme, baseURL, params,
{"Accept": "application/json", "Content-Type": "application/json"});
return router;
}
Я выдает ту же ошибку.
Ответ №1:
Вам нужно изменить params
значение по умолчанию с const {}
на const <String, dynamic>{}
. ваша getRouter
функция должна возвращать Future<Router>
вместо Router
, потому что вам нужно значение authToken
, иначе ваша функция ничего не вернет.
Есть некоторые другие изменения, которые я внес в ваш код, которые вы можете увидеть здесь:
abstract class RouterBase {
HTTPMethod method;
String scheme;
String path;
String baseURL;
Map<String, dynamic> params;
Map<String, dynamic> headers; // change to dynamic
}
class Router implements RouterBase {
HTTPMethod method;
String scheme;
String path;
String baseURL;
Map<String, dynamic> params;
Map<String, dynamic> headers;
Router._(this.method, this.path, this.scheme, this.baseURL, this.params,
this.headers);
static Future<Router> getRouter(
method,
path, {
scheme = "https://",
baseURL = "xyz.com",
params = const <String, dynamic>{}, // add generic types to fix your problem
headers = const {
"Accept": "application/json",
"Content-Type": "application/json"
},
}) async {
Map<String, dynamic> headerValue = HashMap<String, dynamic>.from(headers);
var authToken = await DataModel.shared.authToken;
if (authToken != null) {
headerValue["Authorization"] = authToken;
}
return Router._(method, path, scheme, baseURL, params, headerValue);
}
}