无法使用Flutter项目将DSON映射到Dart中的List

问题描述 投票:0回答:4

我正在运行Flutter 1.0.0(第一版)并且最近升级到1.2.1并且有很多错误和警告我必须纠正。主要指定注释类型。在纠正了所有这些后,我运行了我的Android应用程序,现在将JSON映射到List的代码无效。首先,我将发布有效的原始代码。 JSON数据来自HTTP请求。

api.dart

Future<List<Device>> getDevices() async {
  var response = await _httpNetwork.get(_devicesUrl, headers: {"Cookie": _sessionId});

  if (response.statusCode < 200 || response.statusCode > 400) {
    throw Exception("Error while fetching data");
  }

  final body = json.decode(response.body);

  return body.map<Device>((device) => Device.fromJson(device)).toList();
}

device.dart

class Device {
  Device({
    this.id,
    this.name,
    this.uniqueId,
    this.status,
    this.phone,
    this.model,
    this.disabled,
  });

  factory Device.fromJson(Map<String, dynamic> json) => Device(
        id: json['id'],
        name: json['name'],
        uniqueId: json['uniqueId'],
        status: json['status'] == 'online' ? true : false,
        phone: json['phone'],
        model: json['model'],
        disabled: json['disabled'],
      );

  // API data
  int id;
  String name;
  String uniqueId;
  bool status;
  String phone;
  String model;
  bool disabled;

  Map<String, dynamic> toJson() => <String, dynamic>{
        'id': id,
        'name': name,
        'uniqueId': uniqueId,
        'status': status == true ? 'online' : 'offline',
        'phone': phone,
        'model': model,
        'disabled': disabled,
      };
}

现在,问题出现在api.dart的以下变化。

return json.decode(response.body).map<Device>((Map<String, dynamic> device) => Device.fromJson(device)).toList();

根据Android Studio / Flutter / Dart,这种语法是正确的,但它似乎不起作用。该应用程序不会崩溃,也不会在运行控制台中出现错误,它只是在我的onError调用中点击我的Observable<bool>.fromFuture()代码。

我在我的代码中放了print调用来确定api.dart中的return语句是罪魁祸首。任何人都对此问题有任何见解?

json dart flutter
4个回答
0
投票

我想而不是这个

final body = json.decode(response.body);
  return body.map<Device>((device) => Device.fromJson(device)).toList();

你应该做这个

  final body = json.decode(response.body).cast<Map<String, dynamic>>();
 return body.map<Device>((json) => Device.fromJson(json)).toList();

0
投票

试试这种方式为响应数据制作pojo类。

class UserData {
final int albumId;
final int id;
final String title;
final String url;
final String thumbnailUrl;

UserData({this.albumId, this.id, this.title, this.url, this.thumbnailUrl});

factory UserData.fromJson(Map<String, dynamic> json) {
return new UserData(
    albumId: json['albumId'],
    id: json['id'],
    title: json['title'],
    url: json['url'],
    thumbnailUrl: json['thumbnailUrl']);
}
}

make方法获取数据..

Future<UserData> fetchData() async {
var result = await get('https://jsonplaceholder.typicode.com/photos');

if (result.statusCode == 200) {
 return UserData.fromJson(json.decode(result.body));
} else {
 // If that response was not OK, throw an error.
 throw Exception('Failed to load post');
}
}

现在以这种方式制作列表对象..

 Future<UserData> userDataList;

点击按钮..

            userDataList = fetchData();

您也可以使用以下代码获取数据列表..

List<UserData> list = List();
 var isLoading = false;

void fetchData() async {
setState(() {
  isLoading = true;
});
final response = await get("https://jsonplaceholder.typicode.com/photos");
if (response.statusCode == 200) {
  list = (json.decode(response.body) as List)
      .map((data) => UserData.fromJson(data))
      .toList();
  setState(() {
    isLoading = false;
  });
} else {
  throw Exception('Failed to load photos');
}
}

0
投票

我试过这个代码并且它正在工作,一方面注意,你的statusbool类型,但你给它一个字符串变量,请注意这一点。而且json.decode(response.body)会在代码中添加我添加的示例响应,因此您无需更改它。希望能帮助到你!

class Device {
  Device({
    this.id,
    this.name,
    this.uniqueId,
    this.status,
    this.phone,
    this.model,
    this.disabled,
  });

  factory Device.fromJson(Map<String, dynamic> json) => Device(
        id: json['id'],
        name: json['name'],
        uniqueId: json['uniqueId'],
        status: json['status'] == 'online' ? true : false,
        phone: json['phone'],
        model: json['model'],
        disabled: json['disabled'],
      );

  // API data
  int id;
  String name;
  String uniqueId;
  bool status;
  String phone;
  String model;
  bool disabled;

  Map<String, dynamic> toJson() => <String, dynamic>{
        'id': id,
        'name': name,
        'uniqueId': uniqueId,
        'status': status == true ? 'online' : 'offline',
        'phone': phone,
        'model': model,
        'disabled': disabled,
      };
}




void main() {
  var resp = [{"id": 1, "name": "Pixel", "uniqueId": "439610961385665", 
               "status": "online", "phone": "3215551234", "model": "XL", "disabled": false}];

  List json = resp;
  for(var item in json){
    Device device  = Device.fromJson(item);
    print("nameDevice: ${device.status}");
  }

}

0
投票

这是修复此问题的更改。

return json.decode(response.body).map<Device>((dynamic device) => Device.fromJson(device)).toList();
© www.soinside.com 2019 - 2024. All rights reserved.