flutter 错误提示:需要类型为“Map〈String,dynamic>”的值,但得到的是类型为“String”的值,我该怎么办?

l7wslrjt  于 2023-02-20  发布在  Flutter
关注(0)|答案(2)|浏览(399)

我使用Dio来获取响应,这是我的建模类:

import 'package:shoppingcenter/screens/homePage.dart';

class MALL {
  late final int id;
  late final String name;
  late final String images;

  MALL({required this.id, required this.name, required this.images});

  factory MALL.fromJson(Map<String, dynamic> data) {
    final id = data['id'];
    final name = data['name'];
    final images = data['images'];
    return MALL(id: id, name: name, images: images);
  }
}

class City {
  final List<MALL> malls;

  City({required this.malls});

  factory City.fromJson(Map<String, dynamic> data) {
    final mallData = data['malls'] as List<dynamic>?;
    final malls = mallData != null ? mallData.map((mallData) => MALL.fromJson(mallData)).toList() : <MALL>[];
    return City(malls: malls);
  }
}

当我尝试使用我的类时,我得到这个错误:

Error: Expected a value of type 'Map<String, dynamic>', but got one of type 'String'

我的JSON是:

{
  "malls": [
    {
      "id": 1,
      "name": "city center",
      "images": "city.jpg"
    }
  ]
}

我的响应代码:

Future<List<MALL>> get() async {
  final dio = Dio();
  var url = 'My URL';
  Response response = await dio.get(url);
  City api = City.fromJson(response.data);
  return api.malls;
}

我该怎么办?

q5lcpyga

q5lcpyga1#

从你们的回答中我可以看出:
你的API没有返回JSON,而是返回一个HTML文件。它试图用jsonDecode解析html文件。用Postman检查你的API,为什么它没有返回JSON格式的响应。

nx7onnlm

nx7onnlm2#

response.data是一个String,您需要将其解码为Map

City api = City.fromJson(jsonDecode(response.data));

相关问题