首页 > 解决方案 > Flutter 改造 DioError [DioErrorType.other]:预期类型为 'List 的值?',但得到了“字符串”类型之一

问题描述

我的响应 json 如下

[
{
  "cat_id":"517",
  "categoryName":"Pizza",
  "item" : [
    {
     "itemId" : "1",
     "name": "Pizza 1",
     "price": 50
    },
    {
     "itemId":"2",
     "name" :"Pizza 2",
     "price": 40
    }
  ]
},
{
"cat_id":"518",
  "categoryName":"Burger",
  "item" : [
    {
     "itemId" : "1",
     "name": "Burger 1",
     "price": 10
    },
    {
     "itemId":"2",
     "name" :"Burger 2",
     "price": 30
    }
  ]
  }
 ]

我已经使用如下改造

@RestApi(baseUrl: "https://raw.githubusercontent.com/")
abstract class RestClient {
  factory RestClient(Dio dio) = _RestClient;

  @GET("enamul95/categoryshop/main/lib/util/items.json")
  Future<List<ProductMoel>> getProductItemst();
}

@JsonSerializable()
class ProductMoel {
  String categoryName;
  @JsonKey(name: 'item')
  List<Items> item;
  ProductMoel(this.categoryName, this.item);

  factory ProductMoel.fromJson(Map<String, dynamic> json) =>
      _$ProductMoelFromJson(json);

  Map<String, dynamic> toJson() => _$ProductMoelToJson(this);
}

@JsonSerializable()
class Items extends Object {
  String itemId;
  String name;
   int price;

  Items(this.itemId, this.name,this.price);

  factory Items.fromJson(Map<String, dynamic> json) => _$ItemsFromJson(json);

  Map<String, dynamic> toJson() => _$ItemsToJson(this);
}


    @JsonSerializable()
    class Items extends Object {
      String itemId;
      String name;
      // int price;

      Items(this.itemId, this.name);

      factory Items.fromJson(Map<String, dynamic> json) => _$ItemsFromJson(json);

      Map<String, dynamic> toJson() => _$ItemsToJson(this);
    }

我像下面这样从这里打电话

void getResutrantList(BuildContext context) async {    
final client =  RestClient(Dio(BaseOptions(contentType: "application/json")));
client.getProductItemst().then((it) {     
  print(it);      
}).catchError((error, stackTrace) {     
  print("inner  **********************: $error");
});
}

我的代码有什么问题。请帮助我..

标签: flutterretrofitjson-annotation

解决方案


由于您正在查询文件,我猜 Github 发送的数据没有Content-Type: application/json标头,因此 Dio 将其作为纯文本进行管理。

如果您需要模拟 API,您可以使用在线托管的 MockAPI.io 或本地运行的软件Mockoon 。它应该可以解决您的问题。


推荐阅读