类型“List <dynamic>”不是类型“Map <String,dynamic>”的子类型

Hou*_*sem 5 dart flutter

我正在开发一个依赖于 API REST 调用的 flutter 应用程序。API 的响应有点复杂。\n我可以在调用 API 时看到日志中的响应(例如:api/products):\n但我有此错误:

类型“List<动态>”不是类型“Map<字符串,动态>”的子类型\n

我已经在互联网上看到了所有问题/答案,但没有任何结果。\n我\'我尝试过使用简单的 RestAPI,例如: https: //my-json-server.typicode.com/typicode/demo/posts并且它有效。\n但在我的情况下\nAPI 响应示例:

\n
[\n   {\n      "id":1,\n      "tenant":{\n         "id":1,\n         "code":"company",\n         "name":"company"\n      },\n      "type":{\n         "code":"activity",\n         "name":"Activit\xc3\xa9"\n      },\n      "subType":{\n         "code":"ticket",\n         "name":"Ticket"\n      },\n      "inventoryType":{\n         "code":"external_source",\n         "name":"Source externe"\n      },\n      "externalReference":"CAL6970",\n      "externalSystem":{\n         "code":"koedia",\n         "name":"Koedia"\n      },\n      "active":true,\n      "durationDays":12,\n      "durationNights":14,\n      "durationHours":9,\n      "durationMinutes":10,\n      "supplier":{\n         "id":1,\n         "tenant":{\n            "id":1,\n            "code":"company",\n            "name":"company"\n         },\n         "name":"Jancarthier"\n      },\n      "group":null,\n      "subGroup":null,\n      "name":"H\xc3\xb4tel Koulnou\xc3\xa9 Village",\n      "translations":[\n         {\n            "id":1,\n            "name":"H\xc3\xb4tel Koulnou\xc3\xa9 Village",\n            "locale":"fr"\n         },\n         {\n            "id":24,\n            "name":"H\xc3\xb4tel Koulnou\xc3\xa9 Village",\n            "locale":"en"\n         }\n      ],\n      "vatPercentage":"0.00",\n      "longitude":null,\n      "latitude":null,\n      "departureTime":null,\n      "arrivalTime":null,\n      "arrivalDayPlus":1,\n      "stars":4,\n      "localities":[\n         {\n            "id":41,\n            "locality":{\n               "id":34,\n               "code":"ARM",\n               "name":"Armenia"\n            },\n            "role":{\n               "code":"stop",\n               "name":"Escale"\n            }\n         },\n         {\n            "id":49,\n            "locality":{\n               "id":55,\n               "code":"hossegor",\n               "name":"Hossegor"\n            },\n            "role":{\n               "code":"drop_off",\n               "name":"Retour"\n            }\n         },\n         {\n            "id":50,\n            "locality":{\n               "id":55,\n               "code":"hossegor",\n               "name":"Hossegor"\n            },\n            "role":{\n               "code":"localisation",\n               "name":"Localisation"\n            }\n         }\n      ]\n   }\n]\n
Run Code Online (Sandbox Code Playgroud)\n

堆栈跟踪 :

\n
I/flutter ( 2865): type \'List<dynamic>\' is not a subtype of type \'Map<String, dynamic>\'\n\n
Run Code Online (Sandbox Code Playgroud)\n

[更新]:返回ProductsResponse.fromJson(response)而不是response\nProductsRespository:

\n
import \'dart:async\';\nimport \'package:PROJECT/models/product/ProductResponse.dart\';\nimport \'package:PROJECT/networking/ApiProvider.dart\';\n\nclass ProductRepository {\n  ApiProvider _provider =  ApiProvider();\n\n  Future<ProductsResponse> fetchProducts() async {\n\n      final response = await _provider.getFromApi("products");\n      // here line 11 where exception is thrown\n      return ProductsResponse.fromJson(response);\n  }\n\n\n}\n
Run Code Online (Sandbox Code Playgroud)\n

产品块:

\n
import \'dart:async\';\n\nimport \'package:PROJECT/models/product/ProductResponse.dart\';\n\nimport \'package:PROJECT/networking/Response.dart\';\nimport \'package:PROJECT/repository/ProductRepository.dart\';\n\n\nclass ProductBloc {\n  ProductRepository _productRepository;\n  StreamController _productListController;\n  bool _isStreaming;\n  StreamSink<Response<ProductsResponse>> get productListSink =>\n      _productListController.sink;\n\n\n  Stream<Response<ProductsResponse>> get productListStream =>\n      _productListController.stream;\n\n  ProductBloc() {\n    _productListController = StreamController<Response<ProductsResponse>>();\n    _productRepository = ProductRepository();\n    _isStreaming = true;\n    fetchProducts();\n\n  }\n\n  fetchProducts() async {\n    productListSink.add(Response.loading(\'Getting Products.\'));\n    try {\n     ProductsResponse productsResponse =\n      await _productRepository.fetchProducts();\n     if (_isStreaming) productListSink.add(Response.completed(productsResponse));\n    } catch (e) {\n      if (_isStreaming) productListSink.add(Response.error(e.toString()));\n      print(e);\n    }\n  }\n\n  dispose() {\n    _isStreaming = false;\n    _productListController?.close();\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

回复 :

\n
class Response<T> {\n  Status status;\n  T data;\n  String message;\n\n  Response.loading(this.message) : status = Status.LOADING;\n  Response.completed(this.data) : status = Status.COMPLETED;\n  Response.error(this.message) : status = Status.ERROR;\n\n  @override\n  String toString() {\n    return "Status : $status \\n Message : $message \\n Data : $data";\n  }\n}\n\nenum Status { LOADING, COMPLETED, ERROR }\n
Run Code Online (Sandbox Code Playgroud)\n

API 提供者:

\n
import \'package:PROJECT/networking/CustomException.dart\';\nimport \'package:http/http.dart\' as http;\nimport \'dart:io\';\nimport \'dart:convert\';\nimport \'dart:async\';\n\nclass ApiProvider {\n\n  final String _baseApiUrl = "URL_API/";\n\n  Future<dynamic> getFromApi(String url) async {\n    var responseJson;\n    try {\n      final response = await http.get(Uri.encodeFull(_baseApiUrl + url),headers:{"Accept":"application/json"} );\n      print(response);\n      responseJson = _response(response);\n    } on SocketException {\n      throw FetchDataException(\'No Internet connection\');\n    }\n    return responseJson;\n  }\n\n  dynamic _response(http.Response response) {\n    switch (response.statusCode) {\n      case 200:\n        var responseJson = json.decode(response.body);\n\n        print(responseJson);\n        return responseJson;\n      case 400:\n        throw BadRequestException(response.body.toString());\n      case 401:\n\n      case 403:\n        throw UnauthorisedException(response.body.toString());\n      case 500:\n\n      default:\n        throw FetchDataException(\n            \'Error occured while Communication with Server with StatusCode : ${response.statusCode}\');\n    }\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

型号:产品响应

\n
import \'ExternalSystem.dart\';\nimport \'./InventoryType.dart\';\nimport \'./Localities.dart\';\nimport \'SubType.dart\';\nimport \'Supplier.dart\';\nimport \'Tenant.dart\';\nimport \'./Translation.dart\';\nimport \'./Type.dart\';\n\nclass ProductsResponse {\n    final int id;\n    final Tenant tenant;\n    final Type type;\n    final SubType subType;\n    final InventoryType inventoryType;\n    final String externalReference;\n    final ExternalSystem externalSystem;\n    final bool active;\n    final int durationDays;\n    final int durationNights;\n    final int durationHours;\n    final int durationMinutes;\n    final Supplier supplier;\n    final String name;\n    final List<Translation> translations;\n    final String vatPercentage;\n    final int arrivalDayPlus;\n    final int stars;\n    final List<Localities> localities;\n    final String group;\n    final String subGroup;\n    final double longitude;\n    final double latitude;\n    final String departureTime;\n    final String arrivalTime;\n\n    ProductsResponse({this.id, this.tenant , this.type, this.subType, this.inventoryType, this.externalReference, this.externalSystem, this.active, this.durationDays, this.durationNights, this.durationHours, this.durationMinutes, this.supplier, this.name, this.translations, this.vatPercentage, this.arrivalDayPlus, this.stars, this.localities, this.group, this.subGroup, this.longitude, this.latitude, this.departureTime, this.arrivalTime});\n\n    factory ProductsResponse.fromJson(Map<String, dynamic> json) {\n        return ProductsResponse(\n            id: json[\'id\'],\n            tenant: json[\'tenant\'] != null ? Tenant.fromJson(json[\'tenant\']) : null,\n            type: json[\'type\'] != null ? Type.fromJson(json[\'type\']) : null,\n            subType: json[\'subType\'] != null ? SubType.fromJson(json[\'subType\']) : null,\n            inventoryType: json[\'inventoryType\'] != null ? InventoryType.fromJson(json[\'inventoryType\']) : null,\n            externalReference: json[\'externalReference\'],\n            externalSystem: json[\'externalSystem\'] != null ? ExternalSystem.fromJson(json[\'externalSystem\']) : null,\n            active: json[\'active\']?json[\'active\']:null,\n            durationDays: json[\'durationDays\']?json[\'durationDays\']:null,\n            durationNights: json[\'durationNights\']?json[\'durationNights\']:null,\n            durationHours: json[\'durationHours\']?json[\'durationHours\']:null,\n            durationMinutes: json[\'durationMinutes\']?json[\'durationMinutes\']:null,\n            supplier: json[\'supplier\'] != null ? Supplier.fromJson(json[\'supplier\']) : null,\n            name: json[\'name\']?json[\'name\']:null,\n            translations: json[\'translations\'] != null ? (json[\'translations\'] as List).map((i) => Translation.fromJson(i)).toList() : null,\n            vatPercentage: json[\'vatPercentage\']?json[\'vatPercentage\']:null,\n            arrivalDayPlus: json[\'arrivalDayPlus\']?json[\'arrivalDayPlus\']:null,\n            stars: json[\'stars\']?json[\'stars\']:null,\n            localities: json[\'localities\'] != null ? (json[\'localities\'] as List).map((i) => Localities.fromJson(i)).toList() : null,\n            group: json[\'group\'] != null ? json[\'group\'] : null,\n            subGroup: json[\'subGroup\'] != null ? json[\'subGroup\'] : null,\n            longitude: json[\'longitude\'] != null ? json[\'longitude\'] : null,\n            latitude: json[\'latitude\'] != null ? json[\'latitude\'] : null,\n            departureTime: json[\'departureTime\'] != null ? json[\'departureTime\'] : null,\n            arrivalTime: json[\'arrivalTime\'] != null ? json[\'arrivalTime\'] : null,\n        );\n    }\n\n    Map<String, dynamic> toJson() {\n        final Map<String, dynamic> data = new Map<String, dynamic>();\n        data[\'id\'] = this.id;\n        data[\'externalReference\'] = this.externalReference;\n        data[\'active\'] = this.active;\n        data[\'durationDays\'] = this.durationDays;\n        data[\'durationNights\'] = this.durationNights;\n        data[\'durationHours\'] = this.durationHours;\n        data[\'durationMinutes\'] = this.durationMinutes;\n        data[\'name\'] = this.name;\n        data[\'vatPercentage\'] = this.vatPercentage;\n        data[\'arrivalDayPlus\'] = this.arrivalDayPlus;\n        data[\'stars\'] = this.stars;\n        if (this.tenant != null) {\n            data[\'tenant\'] = this.tenant.toJson();\n        }\n       if (this.type != null) {\n            data[\'type\'] = this.type.toJson();\n        }\n        if (this.subType != null) {\n            data[\'subType\'] = this.subType.toJson();\n        }\n        if (this.inventoryType != null) {\n            data[\'inventoryType\'] = this.inventoryType.toJson();\n        }\n        if (this.externalSystem != null) {\n            data[\'externalSystem\'] = this.externalSystem.toJson();\n        }\n        if (this.supplier != null) {\n            data[\'supplier\'] = this.supplier.toJson();\n        }\n        if (this.translations != null) {\n            data[\'translations\'] = this.translations.map((v) => v.toJson()).toList();\n        }\n        if (this.localities != null) {\n            data[\'localities\'] = this.localities.map((v) => v.toJson()).toList();\n        }\n        if (this.group != null) {\n            data[\'group\'] = this.group;\n        }\n        if (this.subGroup != null) {\n            data[\'subGroup\'] = this.subGroup;\n        }\n        if (this.longitude != null) {\n            data[\'longitude\'] = this.longitude;\n        }\n        if (this.latitude != null) {\n            data[\'latitude\'] = this.latitude;\n        }\n        if (this.departureTime != null) {\n            data[\'departureTime\'] = this.departureTime;\n        }\n        if (this.arrivalTime != null) {\n            data[\'arrivalTime\'] = this.arrivalTime;\n        }\n      print(data);\n\n        return data;\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

[更新]:删除了 ProductsRepository(只能通过 bloc 访问)
\nProductView

\n
import \'package:PROJECT/blocs/ProductBloc.dart\';\nimport \'package:PROJECT/models/product/ProductResponse.dart\';\nimport \'package:PROJECT/networking/Response.dart\';\nimport \'package:PROJECT/repository/ProductRepository.dart\';\nimport \'package:PROJECT/view/widget/Loading.dart\';\nimport \'package:PROJECT/view/widget/ProductList.dart\';\nimport \'package:flutter/material.dart\';\nimport \'package:PROJECT/view/widget/Error.dart\';\n\n\nclass ProductView extends StatefulWidget {\n @override\n _ProductViewState createState() => _ProductViewState();\n}\n\nclass _ProductViewState extends State<ProductView> {\n ProductBloc _bloc = new ProductBloc();\n\n @override\n void initState() {\n   super.initState();\n   _bloc.fetchProducts();\n }\n\n @override\n Widget build(BuildContext context) {\n   return Scaffold(\n     appBar: AppBar(\n       elevation: 0.0,\n       automaticallyImplyLeading: false,\n       title: Text(\'Products\',\n           style: TextStyle(color: Colors.white, fontSize: 20)),\n       backgroundColor: Color(0xFF333333),\n     ),\n     backgroundColor: Color(0xFF333333),\n     body: RefreshIndicator(\n       onRefresh: () => _bloc.fetchProducts(),\n       child: StreamBuilder<Response<ProductsResponse>>(\n         stream: _bloc.productListStream,\n         builder: (context, snapshot) {\n           if (snapshot.hasData) {\n             switch (snapshot.data.status) {\n               case Status.LOADING:\n                 return Loading(loadingMessage: snapshot.data.message);\n                 break;\n               case Status.COMPLETED:\n                 return ProductList(productList:snapshot.data.data);\n                 break;\n               case Status.ERROR:\n                 return Error(\n                   errorMessage: snapshot.data.message,\n                   onRetryPressed: () => _bloc.fetchProducts(),\n                 );\n                 break;\n             }\n           }\n           return Container();\n         },\n       ),\n     ),\n   );\n }\n\n\n}\n\n\n
Run Code Online (Sandbox Code Playgroud)\n

租户示例与其他人相同的逻辑(翻译,类型,子类型..)

\n
class Tenant {\n   final int id;\n   final String code;\n   final String name;\n\n   Tenant({this.id, this.code, this.name});\n\n   factory Tenant.fromJson(Map<String, dynamic> json) {\n       return Tenant(\n           id: json[\'id\'], \n           code: json[\'code\'], \n           name: json[\'name\'], \n       );\n   }\n\n   Map<String, dynamic> toJson() {\n       final Map<String, dynamic> data = new Map<String, dynamic>();\n       data[\'id\'] = this.id;\n       data[\'code\'] = this.code;\n       data[\'name\'] = this.name;\n       return data;\n   }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

chu*_*han 5

您可以在下面复制粘贴运行完整代码
\n因为您的 json 字符串产生一个List<ProductResponse>not ProductResponse
\n在您的代码中您可以直接返回response.bodyasString并解析productsResponseFromJson

\n\n

代码片段

\n\n
List<ProductsResponse> productsResponseFromJson(String str) =>\nList<ProductsResponse>.from(\n    json.decode(str).map((x) => ProductsResponse.fromJson(x)));\n\nFuture<List<ProductsResponse>> fetchProducts() async {\n  ApiProvider _provider = ApiProvider();\n  String response = await _provider.getFromApi("products");\n  // here line 11 where exception is thrown\n  return productsResponseFromJson(response);\n  //return ProductsResponse.fromJson(response);\n}\n\nFuture<String> getFromApi(String url) async {\n\nString _response(http.Response response) {\n    switch (response.statusCode) {\n      case 200:\n        print(response.body);\n        //var responseJson = jsonDecode(response.body);\n\n        //print(responseJson);\n        return response.body;\n
Run Code Online (Sandbox Code Playgroud)\n\n

工作演示

\n\n

在此输入图像描述

\n\n

完整代码

\n\n
import \'package:flutter/material.dart\';\nimport \'package:http/http.dart\' as http;\n// To parse this JSON data, do\n//\n//     final productsResponse = productsResponseFromJson(jsonString);\n\nimport \'dart:convert\';\n\nList<ProductsResponse> productsResponseFromJson(String str) =>\n    List<ProductsResponse>.from(\n        json.decode(str).map((x) => ProductsResponse.fromJson(x)));\n\nString productsResponseToJson(List<ProductsResponse> data) =>\n    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));\n\nclass ProductsResponse {\n  int id;\n  Tenant tenant;\n  ExternalSystem type;\n  ExternalSystem subType;\n  ExternalSystem inventoryType;\n  String externalReference;\n  ExternalSystem externalSystem;\n  bool active;\n  int durationDays;\n  int durationNights;\n  int durationHours;\n  int durationMinutes;\n  Supplier supplier;\n  dynamic group;\n  dynamic subGroup;\n  String name;\n  List<Translation> translations;\n  String vatPercentage;\n  dynamic longitude;\n  dynamic latitude;\n  dynamic departureTime;\n  dynamic arrivalTime;\n  int arrivalDayPlus;\n  int stars;\n  List<Locality> localities;\n\n  ProductsResponse({\n    this.id,\n    this.tenant,\n    this.type,\n    this.subType,\n    this.inventoryType,\n    this.externalReference,\n    this.externalSystem,\n    this.active,\n    this.durationDays,\n    this.durationNights,\n    this.durationHours,\n    this.durationMinutes,\n    this.supplier,\n    this.group,\n    this.subGroup,\n    this.name,\n    this.translations,\n    this.vatPercentage,\n    this.longitude,\n    this.latitude,\n    this.departureTime,\n    this.arrivalTime,\n    this.arrivalDayPlus,\n    this.stars,\n    this.localities,\n  });\n\n  factory ProductsResponse.fromJson(Map<String, dynamic> json) =>\n      ProductsResponse(\n        id: json["id"],\n        tenant: Tenant.fromJson(json["tenant"]),\n        type: ExternalSystem.fromJson(json["type"]),\n        subType: ExternalSystem.fromJson(json["subType"]),\n        inventoryType: ExternalSystem.fromJson(json["inventoryType"]),\n        externalReference: json["externalReference"],\n        externalSystem: ExternalSystem.fromJson(json["externalSystem"]),\n        active: json["active"],\n        durationDays: json["durationDays"],\n        durationNights: json["durationNights"],\n        durationHours: json["durationHours"],\n        durationMinutes: json["durationMinutes"],\n        supplier: Supplier.fromJson(json["supplier"]),\n        group: json["group"],\n        subGroup: json["subGroup"],\n        name: json["name"],\n        translations: List<Translation>.from(\n            json["translations"].map((x) => Translation.fromJson(x))),\n        vatPercentage: json["vatPercentage"],\n        longitude: json["longitude"],\n        latitude: json["latitude"],\n        departureTime: json["departureTime"],\n        arrivalTime: json["arrivalTime"],\n        arrivalDayPlus: json["arrivalDayPlus"],\n        stars: json["stars"],\n        localities: List<Locality>.from(\n            json["localities"].map((x) => Locality.fromJson(x))),\n      );\n\n  Map<String, dynamic> toJson() => {\n        "id": id,\n        "tenant": tenant.toJson(),\n        "type": type.toJson(),\n        "subType": subType.toJson(),\n        "inventoryType": inventoryType.toJson(),\n        "externalReference": externalReference,\n        "externalSystem": externalSystem.toJson(),\n        "active": active,\n        "durationDays": durationDays,\n        "durationNights": durationNights,\n        "durationHours": durationHours,\n        "durationMinutes": durationMinutes,\n        "supplier": supplier.toJson(),\n        "group": group,\n        "subGroup": subGroup,\n        "name": name,\n        "translations": List<dynamic>.from(translations.map((x) => x.toJson())),\n        "vatPercentage": vatPercentage,\n        "longitude": longitude,\n        "latitude": latitude,\n        "departureTime": departureTime,\n        "arrivalTime": arrivalTime,\n        "arrivalDayPlus": arrivalDayPlus,\n        "stars": stars,\n        "localities": List<dynamic>.from(localities.map((x) => x.toJson())),\n      };\n}\n\nclass ExternalSystem {\n  String code;\n  String name;\n\n  ExternalSystem({\n    this.code,\n    this.name,\n  });\n\n  factory ExternalSystem.fromJson(Map<String, dynamic> json) => ExternalSystem(\n        code: json["code"],\n        name: json["name"],\n      );\n\n  Map<String, dynamic> toJson() => {\n        "code": code,\n        "name": name,\n      };\n}\n\nclass Locality {\n  int id;\n  Tenant locality;\n  ExternalSystem role;\n\n  Locality({\n    this.id,\n    this.locality,\n    this.role,\n  });\n\n  factory Locality.fromJson(Map<String, dynamic> json) => Locality(\n        id: json["id"],\n        locality: Tenant.fromJson(json["locality"]),\n        role: ExternalSystem.fromJson(json["role"]),\n      );\n\n  Map<String, dynamic> toJson() => {\n        "id": id,\n        "locality": locality.toJson(),\n        "role": role.toJson(),\n      };\n}\n\nclass Tenant {\n  int id;\n  String code;\n  String name;\n\n  Tenant({\n    this.id,\n    this.code,\n    this.name,\n  });\n\n  factory Tenant.fromJson(Map<String, dynamic> json) => Tenant(\n        id: json["id"],\n        code: json["code"],\n        name: json["name"],\n      );\n\n  Map<String, dynamic> toJson() => {\n        "id": id,\n        "code": code,\n        "name": name,\n      };\n}\n\nclass Supplier {\n  int id;\n  Tenant tenant;\n  String name;\n\n  Supplier({\n    this.id,\n    this.tenant,\n    this.name,\n  });\n\n  factory Supplier.fromJson(Map<String, dynamic> json) => Supplier(\n        id: json["id"],\n        tenant: Tenant.fromJson(json["tenant"]),\n        name: json["name"],\n      );\n\n  Map<String, dynamic> toJson() => {\n        "id": id,\n        "tenant": tenant.toJson(),\n        "name": name,\n      };\n}\n\nclass Translation {\n  int id;\n  String name;\n  String locale;\n\n  Translation({\n    this.id,\n    this.name,\n    this.locale,\n  });\n\n  factory Translation.fromJson(Map<String, dynamic> json) => Translation(\n        id: json["id"],\n        name: json["name"],\n        locale: json["locale"],\n      );\n\n  Map<String, dynamic> toJson() => {\n        "id": id,\n        "name": name,\n        "locale": locale,\n      };\n}\n\nvoid main() {\n  runApp(MyApp());\n}\n\nFuture<List<ProductsResponse>> fetchProducts() async {\n  ApiProvider _provider = ApiProvider();\n  String response = await _provider.getFromApi("products");\n  // here line 11 where exception is thrown\n  return productsResponseFromJson(response);\n  //return ProductsResponse.fromJson(response);\n}\n\nclass ApiProvider {\n  Future<String> getFromApi(String url) async {\n    var responseJson;\n    try {\n      //final response = await http.get(Uri.encodeFull(_baseApiUrl + url),headers:{"Accept":"application/json"} );\n      String jsonString = \'\'\'\n      [\n   {\n      "id":1,\n      "tenant":{\n         "id":1,\n         "code":"company",\n         "name":"company"\n      },\n      "type":{\n         "code":"activity",\n         "name":"Activit\xc3\xa9"\n      },\n      "subType":{\n         "code":"ticket",\n         "name":"Ticket"\n      },\n      "inventoryType":{\n         "code":"external_source",\n         "name":"Source externe"\n      },\n      "externalReference":"CAL6970",\n      "externalSystem":{\n         "code":"koedia",\n         "name":"Koedia"\n      },\n      "active":true,\n      "durationDays":12,\n      "durationNights":14,\n      "durationHours":9,\n      "durationMinutes":10,\n      "supplier":{\n         "id":1,\n         "tenant":{\n            "id":1,\n            "code":"company",\n            "name":"company"\n         },\n         "name":"Jancarthier"\n      },\n      "group":null,\n      "subGroup":null,\n      "name":"H\xc3\xb4tel Koulnou\xc3\xa9 Village",\n      "translations":[\n         {\n            "id":1,\n            "name":"H\xc3\xb4tel Koulnou\xc3\xa9 Village",\n            "locale":"fr"\n         },\n         {\n            "id":24,\n            "name":"H\xc3\xb4tel Koulnou\xc3\xa9 Village",\n            "locale":"en"\n         }\n      ],\n      "vatPercentage":"0.00",\n      "longitude":null,\n      "latitude":null,\n      "departureTime":null,\n      "arrivalTime":null,\n      "arrivalDayPlus":1,\n      "stars":4,\n      "localities":[\n         {\n            "id":41,\n            "locality":{\n               "id":34,\n               "code":"ARM",\n               "name":"Armenia"\n            },\n            "role":{\n               "code":"stop",\n               "name":"Escale"\n            }\n         },\n         {\n            "id":49,\n            "locality":{\n               "id":55,\n               "code":"hossegor",\n               "name":"Hossegor"\n            },\n            "role":{\n               "code":"drop_off",\n               "name":"Retour"\n            }\n         },\n         {\n            "id":50,\n            "locality":{\n               "id":55,\n               "code":"hossegor",\n               "name":"Hossegor"\n            },\n            "role":{\n               "code":"localisation",\n               "name":"Localisation"\n            }\n         }\n      ]\n   }\n]\n    \'\'\';\n\n      http.Response response = http.Response(jsonString, 200);\n      print(response);\n      responseJson = _response(response);\n    } on Exception {\n      //throw FetchDataException(\'No Internet connection\');\n    }\n    return responseJson;\n  }\n\n  String _response(http.Response response) {\n    switch (response.statusCode) {\n      case 200:\n        print(response.body);\n        //var responseJson = jsonDecode(response.body);\n\n        //print(responseJson);\n        return response.body;\n      /* case 400:\n        throw BadRequestException(response.body.toString());\n      case 401:\n\n      case 403:\n        throw UnauthorisedException(response.body.toString());\n      case 500:\n\n      default:\n        throw FetchDataException(\n            \'Error occured while Communication with Server with StatusCode : ${response.statusCode}\');*/\n    }\n  }\n}\n\nclass MyApp extends StatelessWidget {\n  @override\n  Widget build(BuildContext context) {\n    return MaterialApp(\n      title: \'Flutter Demo\',\n      theme: ThemeData(\n        primarySwatch: Colors.blue,\n      ),\n      home: MyHomePage(title: \'Flutter Demo Home Page\'),\n    );\n  }\n}\n\nclass MyHomePage extends StatefulWidget {\n  MyHomePage({Key key, this.title}) : super(key: key);\n\n  final String title;\n\n  @override\n  _MyHomePageState createState() => _MyHomePageState();\n}\n\nclass _MyHomePageState extends State<MyHomePage> {\n  int _counter = 0;\n  List<ProductsResponse> productResponseList;\n\n  void _incrementCounter() async {\n    productResponseList = await fetchProducts();\n    print(\'${productResponseList[0].inventoryType}\');\n    setState(() {\n      _counter++;\n    });\n  }\n\n  @override\n  void initState() {\n    // TODO: implement initState\n    super.initState();\n  }\n\n  @override\n  Widget build(BuildContext context) {\n    return Scaffold(\n      appBar: AppBar(\n        title: Text(widget.title),\n      ),\n      body: Center(\n        child: Column(\n          mainAxisAlignment: MainAxisAlignment.center,\n          children: <Widget>[\n            productResponseList == null\n                ? CircularProgressIndicator()\n                : Text(\'${productResponseList[0].inventoryType.name}\'),\n            Text(\n              \'You have pushed the button this many times:\',\n            ),\n            Text(\n              \'$_counter\',\n              style: Theme.of(context).textTheme.headline4,\n            ),\n          ],\n        ),\n      ),\n      floatingActionButton: FloatingActionButton(\n        onPressed: _incrementCounter,\n        tooltip: \'Increment\',\n        child: Icon(Icons.add),\n      ),\n    );\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n