我一直在嘗試除錯此錯誤型別“空”不是型別轉換中“字串”型別的子型別,但找不到產生錯誤的確切位置,除了它是在觸發 POST API 呼叫時生成的.
店鋪類
import 'package:freezed_annotation/freezed_annotation.dart';
part 'shop.freezed.dart';
part 'shop.g.dart';
@freezed
class Shop with _$Shop {
factory Shop({
String? id,
@JsonKey(name: 'shopNumber')String? number,
@JsonKey(name: 'created') String? createdAt,
@JsonKey(name: 'updated') String? updatedAt,
int? calendar}) = _Shop;
factory Shop.fromJson(Map<String, dynamic> json) => _$ShopFromJson(json);
static Shop fromJsonModel(Map<String, dynamic> json) => Shop.fromJson(json);
}
后期功能 - 創建店鋪
Future<void> postShop() async {
Shop shop;
shop = await shopSvc.create(Shop(calendar: widget.calendar?.id, number: _shopNumber));
var newCalendar = widget.calendar?.copyWith(shop: shop);
Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => ShopInfoScreen(calendar: newCalendar!)));
}
} catch (e) {
print(e);
}
}
}
店鋪服務檔案
class ShopService extends BaseHttpService {
final AppContext appContext;
late String _shopApi;
shopService(http.Client client, this.appContext) : super(httpClient: client) {
_shopApi = '${Globals.ApiEndpoint}/user/${appContext.currentCustomer.id}/shops/';
}
Future<Shop> create(Shop shop) async {
var token = await this.appContext.currentUser!.getIdToken();
final response = await callApi('$_cardApi/', token, method: 'post', payload: shop.toJson());
// return Shop.fromJsonModel(json.decode(response));
return shop;
}
}
基本 Http 服務檔案
class BaseHttpService {
final Client httpClient;
BaseHttpService({required this.httpClient});
@protected
Future<String> callApi(String url, String token, {String method: 'get', Map<String, dynamic>? payload}) async {
late Response response;
Map<String, String> headers = {'Authorization': 'Bearer $token'};
if (method == 'get') response = await httpClient.get(Uri.parse(url), headers: headers);
else if (method == 'post') response = await httpClient.post(Uri.parse(url), headers: headers, body: payload);
else if (method == 'put') response = await httpClient.put(Uri.parse(url), headers: headers, body: payload);
else if (method == 'delete') response = await httpClient.delete(Uri.parse(url), headers: headers);
if (response.statusCode >= 300) {
print('statusCode : ' response.statusCode.toString());
print(response.body.toString());
throw ClientException('Failed to load story with id $url');
}
return response.body;
}
}
基本上我想要做的就是創建只需要正文中的 2 個欄位的商店,number而calendar其他欄位將在資料庫中默認。
代碼在這一行的末尾失敗,else if (method == 'post') response = await httpClient.post(Uri.parse(url), headers: headers, body: payload); 但我不知道問題出?在哪里,因為我已經輸入了變數。
http 包已經是最新版本 http: ^0.13.4
我已經在 POSTMAN 中為 POST 呼叫嘗試了以下正文,它可以正常作業:
//Test 1
{
"id": null,
"shopNumber": "87678675",
"created": null,
"updated": null,
"calendar": 1
}
//Test 2
{
"shopNumber": "87678675",
"calendar": 1
}
堆疊跟蹤:
#0 CastMap.forEach.<anonymous closure> (dart:_internal/cast.dart:288:25)
#1 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:400:8)
#2 CastMap.forEach (dart:_internal/cast.dart:287:13)
#3 mapToQuery (package:http/src/utils.dart:17:7)
#4 Request.bodyFields= (package:http/src/request.dart:137:12)
#5 BaseClient._sendUnstreamed (package:http/src/base_client.dart:87:17)
#6 BaseClient.post (package:http/src/base_client.dart:32:7)
#7 BaseHttpService.callApi (package:shop/services/base-http.dart:18:60)
#8 ShopService.create (package:shop/services/shop_service.dart:20:28)
<asynchronous suspension>
#9 _ShopAddScreenState.postShop (package:shop/shop_add_screen.dart:137:16)
<asynchronous suspension>
uj5u.com熱心網友回復:
您可能正在Null從您的 api 呼叫中發送/獲取價值,但它與您的 type 不匹配string。或欄位名稱不相同。請檢查value和欄位名稱。
uj5u.com熱心網友回復:
更改以下http-0.13.4/lib/src/utils.dart 中的代碼片段對錯誤進行了排序:“type 'Null' is not a subtype of type 'String' in type cast”。參考我得到此代碼的 github 問題https://github.com/dart-lang/http/issues/75
這將從有效負載中洗掉所有空值,或者您可以在其中放置一些其他代碼來管理空值。
從:
String mapToQuery(Map<String, String> map, {Encoding encoding}) {
var pairs = <List<String>>[];
map.forEach((key, value) =>
pairs.add([Uri.encodeQueryComponent(key, encoding: encoding),
Uri.encodeQueryComponent(value, encoding: encoding)]));
return pairs.map((pair) => "${pair[0]}=${pair[1]}").join("&");
}
到:
String mapToQuery(Map<String, String> map, {Encoding encoding}) {
map.keys
.where((k) => (map[k] == null)).toList() // -- keys for null elements
.forEach(map.remove);
var pairs = <List<String>>[];
map.forEach((key, value) =>
pairs.add([Uri.encodeQueryComponent(key, encoding: encoding),
Uri.encodeQueryComponent(value, encoding: encoding)]));
return pairs.map((pair) => "${pair[0]}=${pair[1]}").join("&");
}
enter code here
在解決了“型別 'int' 不是型別轉換中的型別 'String' 的子型別”之后,我還遇到了另一個類似的錯誤。我相信這是由于 http-0.13.4/lib/src/utils.dart 中的這段代碼,http 客戶端嘗試將所有內容映射到字串,如上所述。
String mapToQuery(Map<String, String> map, {Encoding encoding})
為了避免所有這些問題,我只是改變了我的功能:
從:
Future<String> callApi(String url, String token, {String method: 'get', Map<String, dynamic>? payload})
到:
Future<String> callApi(String url, String token, {String method: 'get', String? payload})
然后shop.toJson()我沒有使用,而是將其替換為json.encode(shop)
Future<Shop> create(Shop shop) async {
var token = await this.appContext.currentUser!.getIdToken();
final response = await callApi('$_cardApi/', token, method: 'post', payload: json.encode(shop));
// return Shop.fromJsonModel(json.decode(response));
return shop;
}
通過將有效負載更改為 aString而不是Map觸發不同的輸出,如您在http-0.13.4/lib/src/base_client.dart中的這段代碼中所見
if (headers != null) request.headers.addAll(headers);
if (encoding != null) request.encoding = encoding;
if (body != null) {
if (body is String) {
request.body = body;
} else if (body is List) {
request.bodyBytes = body.cast<int>();
} else if (body is Map) {
request.bodyFields = body.cast<String, String>();
} else {
throw ArgumentError('Invalid request body "$body".');
}
以前我正在觸發body is Map將值轉換為字串:
else if (body is Map) {
request.bodyFields = body.cast<String, String>();
}
這是將 mynull和intvalues 轉換String為導致兩個錯誤的值。
現在我正在觸發:
if (body is String) {
request.body = body;
}
希望這可以幫助將來遇到此問題的人。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/387096.html
