我正在嘗試將來自第三方網站的 json 資料寫在一個平面上,但我已經嘗試了不同的選項。我在最后一步遇到了同樣的問題。請幫幫我。
我有這個模型
class SkinModel {
String src;
String name;
double minprice;
int count;
double avgprice;
double medianprice;
int popularity;
SkinModel(
{required this.src,
required this.name,
required this.minprice,
required this.count,
required this.avgprice,
required this.medianprice,
required this.popularity});
factory SkinModel.fromJson(Map<String, dynamic> json) {
return SkinModel(
src: json['src'],
name: json['name'],
minprice: json['minprice'],
count: json['count'],
avgprice: json['avgprice'],
medianprice: json['medianprice'],
popularity: json['popularity'],
);
}
}
以及這樣一個用于接收和處理資料的類
import 'dart:convert';
import 'package:flutter_application_1/data_skins.dart';
import 'package:flutter_application_1/model/model_skin.dart';
import 'package:http/http.dart' as http;
class Skins {
Future<dynamic>? getSkinsPopular(String game, String? method) async {
late List<SkinModel> skinListModel = [];
if (method == null) {
skinListModel = skinssamplelist;
}
String url = 'https://market.dota2.net/api/v2/prices/USD.json';
print('Step 1 ' url);
http.Response response = await http.get(
Uri.parse(url),
);
print('Step 2 ' response.reasonPhrase!);
if (response.statusCode == 200) {
var decodeData = json.decode(response.body);
var rest = decodeData['items'] as List;
print('Step 3');
print(rest);
skinListModel =
rest.map<SkinModel>((json) => SkinModel.fromJson(json)).toList();
print('Step 4');
print(skinListModel);
} else {
throw 'Problem with get request';
}
return skinListModel;
}
}
}
但是最后成功的第3步和除錯器寫入flutter后:對不起重試我絕對不明白錯誤是什么以及我做錯了什么
uj5u.com熱心網友回復:
late List<SkinModel> skinListModel = [];
String url = 'https://market.dota2.net/api/v2/prices/USD.json';
print('Step 1 ' url);
http.Response response = await http.get(
Uri.parse(url),
);
print('Step 2 ' response.reasonPhrase!);
if (response.statusCode == 200) {
var decodeData = jsonDecode(response.body);
var rest = decodeData['items'] as List;
print('Step 3');
print(rest);
for (var element in rest) {skinListModel.add(SkinModel.fromJson(element)); } //replace this line
print('Step 4');
print(skinListModel);
} else {
throw 'Problem with get request';
}
uj5u.com熱心網友回復:
您正在嘗試向https://market.dota2.net/api/v2/prices/USD.json發送請求,它會回傳 items 物件陣列。物件具有欄位:
market_hash_name: String,
volume: String,
price: String,
在您的代碼中,您嘗試決議 json,但您的 SkinModel 具有以下欄位:
String src;
String name;
double minprice;
int count;
double avgprice;
double medianprice;
int popularity;
在將 json 轉換為 SkinModel 時,您嘗試從不存在的欄位中獲取值。錯誤發生在這一行。
src: json['src'], // You try to get src but it does not exist
Flutter 說你不能將 null 轉換為 String。
_TypeError (type 'Null' is not a subtype of type 'String')
為了修復錯誤,請使用另一個 api url。或將您的模型更改為:
class SkinModel {
final String market_hash_name;
final String volume;
final String price;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/527905.html
標籤:扑镖
下一篇:撲。文本溢位