【问题标题】:'_TypeError' is not a subtype of type 'String' error Flutter Map'_TypeError' 不是类型 'String' 错误 Flutter Map 的子类型
【发布时间】:2025-12-15 08:30:01
【问题描述】:

我想从 Response 中获取 Map

我的对象是

    class Product{
      String id;
      String title;
      double price;
      String image;
      bool sc;
    
      Product({@required this.id, @required this.title, @required this.price,
        @required this.image, @required this.sc});
    
      factory Product.fromJson(Map<String, dynamic> json) {
        return Product(
          id: json['id'] as String,
          title: json['title'] as String,
          price: json['price'] as double,
          image: json['image'] as String,
          sc: json['sc'] as bool,
        );
      }
    }

Http 代码在这里

    Future<Map<String, List<Product>>> fetchProduct(String url) async{
    dio.Dio d = new dio.Dio();

    Map<String, dynamic> headers = new Map();
    headers['Cookie'] = "JSESSIONID=" + SessionUtils().getSession().toString();
    dio.Options options = new dio.Options(
      headers: headers,
      contentType: 'application/json'
    );

    dio.Response response = await d.get(url, options: options);

    print(response.data);
    if(response.statusCode == HttpStatus.ok){
      return json.decode(response.data); // need help here
    }
  
  } 

我收到了错误I/flutter (20085): Another exception was thrown: type '_TypeError' is not a subtype of type 'String'

谢谢!

【问题讨论】:

  • 你能找到Product类中的哪一行产生了这个错误吗?错误可能来自 id、title 或 image

标签: flutter dart


【解决方案1】:

API Reference for DIO

在他们的 API 参考中,他们提到您必须在选项中设置一个 responseType。默认是 JSON,所以也许你可以直接返回 response.data,因为它已经被反序列化为 map。

另一个选项可能是:

responseType = responseType.string;

在 dio 选项中,然后您将获得可以手动解码的字符串形式的 response.data。

我从未使用过 DIO,但根据 API 参考,这似乎是问题所在,因为错误表明 json.decode() 需要一个字符串但得到了一个映射,因此 response.data 可能是动态的,并且数据类型会根据更改在指定的 responseType 上。试试看!

【讨论】:

    最近更新 更多