Flutter调用REST API遇'type int is not a subtype of string'错误求助
问题原因及修正方案
你遇到的type 'int' is not a subtype of 'string'错误,加上代码里的其他问题,主要出在这几个地方:
字段类型完全不匹配
- API返回的
status是整数(200),但你模型里把它定义成了String类型,赋值时直接把int塞给String,触发类型转换错误 - API里的
uuid是字符串格式的UUID(比如"85ad13f7-3d1b-5128-9eb2-7cd8ee0b5741"),你却把模型里的uuid定义成int还去int.parse,这完全不符合数据结构
- API返回的
响应结构解析错误
API返回的data是一个数组(包含多个货币对象),但你当前的模型试图直接从json['data']['uuid']取单个对象的字段,这根本取不到正确数据,还会引发额外错误字段拼写错误
模型里的assestPath少写了一个s,应该是assetPath,对应API里的字段名,否则会拿到null值
修正后的代码
1. 拆分模型(总响应+单个货币)
先定义单个货币的模型:
class Currency { final String uuid; final String displayName; final String displayNameSingular; final String displayIcon; final String largeIcon; final String assetPath; const Currency({ required this.uuid, required this.assetPath, required this.displayIcon, required this.displayName, required this.displayNameSingular, required this.largeIcon, }); factory Currency.fromJson(Map<String, dynamic> json) { return Currency( uuid: json['uuid'], assetPath: json['assetPath'], displayIcon: json['displayIcon'], displayName: json['displayName'], displayNameSingular: json['displayNameSingular'], largeIcon: json['largeIcon'], ); } }
再定义整个API响应的模型:
class CurrencyResponse { final int status; final List<Currency> data; const CurrencyResponse({ required this.status, required this.data, }); factory CurrencyResponse.fromJson(Map<String, dynamic> json) { // 把数组转成Currency列表 final currencyList = (json['data'] as List) .map((item) => Currency.fromJson(item)) .toList(); return CurrencyResponse( status: json['status'], data: currencyList, ); } }
2. 修改数据获取方法
import 'dart:convert'; import 'package:http/http.dart' as http; import 'package:valoranttools/models/models.dart'; Future<CurrencyResponse> fetchCurrencies() async { final response = await http.get(Uri.parse('https://valorant-api.com/v1/currencies')); if (response.statusCode == 200) { return CurrencyResponse.fromJson(jsonDecode(response.body)); } else { throw Exception('加载货币数据失败'); } }
这样修改后,就能正确解析API返回的数组数据,同时解决所有类型不匹配的问题。
内容的提问来源于stack exchange,提问作者MatDoak
相关产品推荐
相关产品推荐

