我遇到了类型问题,我不知道我做错了什么,我正在尝试将数据存储在 GetX 控制器类中并使其可观察。
我的代码:-
import 'package:get/get.dart';
import '../Services/HttpService.dart';
import 'dart:convert';
class SelectedCardController extends GetxController{
var selectedProductList = List().obs;
@override
void onInit() async{
super.onInit();
getProductDetail();
}
selectedProduct() async {
try {
HttpService httpService = HttpService();
var response = await httpService.get('business', 'product', 'get', '6035de62bf7db17c5dfd9977');
Map<dynamic, dynamic> decodedResponse = json.decode(response);
print('res ----------------- $decodedResponse');
print(selectedProductList.runtimeType);
if (decodedResponse['code'] == 200) selectedProductList = decodedResponse['content'];
print("result ------ $selectedProductList");
}
catch (e) {print(e);}
}
提前感谢您的帮助
答案 0 :(得分:0)
首先,您尝试使用列表来转换原始 JSON 数据,但您应该改用地图。我的建议是您应该首先创建一个模型,以便将 JSON 数据转换为该模型的实例。查看 Flutter 文档以供参考:https://flutter.dev/docs/cookbook/networking/background-parsing#create-a-photo-class
有一个非常好的工具可以帮助您自动创建模型,只需粘贴 JSON 数据,它就会为您生成正确的模型:https://javiercbk.github.io/json_to_dart/
但是,如果您仍在学习,我建议您暂时尝试手动创建模型,这对练习很有帮助。
一旦你这样做了,你可以简单地用 var selectedProductList = decodedResponse['content'];
替换 Content selectedProductList = Content.fromJson(decodedResponse['content']);
如果您仍然收到类似的错误消息,您也可以尝试Content selectedProductList = Content.fromJson(Map.from(decodedResponse['content']));
答案 1 :(得分:0)
更改以下行:
Map<dynamic, dynamic> decodedResponse = json.decode(response);
为此:
Map<String, dynamic> decodedResponse = json.decode(response);
答案 2 :(得分:0)
终于成功了 - 感谢所有在这个问题上花费时间的人
import 'package:get/get.dart';
import '../Services/HttpService.dart';
import 'dart:convert';
class SelectedCardController extends GetxController{
var selectedProductList = Map().obs;
@override
void onInit() async{
super.onInit();
getProductDetail();
}
getProductDetail() async {
try {
HttpService httpService = HttpService();
var response = await httpService.get('business', 'product','get',
'6035de62bf7db17c5dfd9977');
Map<String, dynamic> decodedResponse = json.decode(response);
if (decodedResponse['code'] == 200) selectedProductList.value =
decodedResponse['content'] ;
print("sdbcdbck--------------$selectedProductList");
}
catch (e) {print(e);}
}