я получил эту ошибку "Необработанное исключение: тип 'String' не является подтипом типа 'Map «в типе литья», как показано ниже - PullRequest
0 голосов
/ 29 апреля 2020

[это снимок с ошибки]


** это код провайдера, который я использую для получения данных с сервера, и возникает ошибка Unhandled Exception: тип 'String' не является подтипом типа 'Map' при приведении типа: *****

Future<void> fetchUserOrders () async{
    final prefs = await SharedPreferences.getInstance();
    String accessToken = prefs.getString(Constants.prefsUserAccessTokenKey);
    print("accessToken :" +accessToken);
    final url = Urls.fetchUserOrders;
    final response = await retry(()=>
      http.get(url, headers: {
        "Accept": "application/json",
        "Authorization": "Bearer " + accessToken
      }
      ).timeout(Duration(seconds: 10)),
      retryIf: (error)=> error is SocketException || error is TimeoutException,
      );
      final List<Order> loadedOrders = [];
      final extractData = json.encode(response.body) as Map<String, dynamic>;
      extractData.forEach((orderId, orderData){
        loadedOrders.add(Order.fromJson(extractData));
      });
      _orders = loadedOrders;
      notifyListeners();
}

это код модели, который я использую для обработки запроса get

import 'order_item.dart';

class Order {
  int id;
  String userName;
  String userMobile;
  int numberOfItems;
  String orderSummary;
  int price;
  String currentStatus;
  String address;
  int vatAmount;
  int serviceTax;
  int delivery;
  int discountValue;
  String restaurantName;
  int restaurantId;
  String branchName;
  List<OrderItem> orderItems;
  String orderComment;
  bool inBranch;

  Order(
      {this.id,
      this.userName,
      this.userMobile,
      this.numberOfItems,
      this.orderSummary,
      this.price,
      this.currentStatus,
      this.address,
      this.vatAmount,
      this.serviceTax,
      this.delivery,
      this.discountValue,
      this.restaurantName,
      this.restaurantId,
      this.branchName,
      this.orderItems,
      this.orderComment,
      this.inBranch});
******************************

для передачи данных с сервера

  Order.fromJson(Map<String, dynamic> json) {
    id = json['Id'];
    userName = json['UserName'];
    userMobile = json['UserMobile'];
    numberOfItems = json['NumberOfItems'];
    orderSummary = json['OrderSummary'];
    price = json['Price'];
    currentStatus = json['CurrentStatus'];
    address = json['Address'];
    vatAmount = json['VatAmount'];
    serviceTax = json['ServiceTax'];
    delivery = json['Delivery'];
    discountValue = json['DiscountValue'];
    restaurantName = json['RestaurantName'];
    restaurantId = json['RestaurantId'];
    branchName = json['BranchName'];
    if (json['orderItems'] != null) {
      orderItems = new List<OrderItem>();
      json['orderItems'].forEach((v) {
        orderItems.add(new OrderItem.fromJson(v));
      });
    }
    orderComment = json['OrderComment'];
    inBranch = json['InBranch'];
  }

для передачи данных в сервер

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['Id'] = this.id;
    data['UserName'] = this.userName;
    data['UserMobile'] = this.userMobile;
    data['NumberOfItems'] = this.numberOfItems;
    data['OrderSummary'] = this.orderSummary;
    data['Price'] = this.price;
    data['CurrentStatus'] = this.currentStatus;
    data['Address'] = this.address;
    data['VatAmount'] = this.vatAmount;
    data['ServiceTax'] = this.serviceTax;
    data['Delivery'] = this.delivery;
    data['DiscountValue'] = this.discountValue;
    data['RestaurantName'] = this.restaurantName;
    data['RestaurantId'] = this.restaurantId;
    data['BranchName'] = this.branchName;
    if (this.orderItems != null) {
      data['orderItems'] = this.orderItems.map((v) => v.toJson()).toList();
    }
    data['OrderComment'] = this.orderComment;
    data['InBranch'] = this.inBranch;
    return data;
  }
}

1 Ответ

0 голосов
/ 29 апреля 2020
final extractData = json.encode(response.body) as Map<String, dynamic>;

должно быть

final extractData = json.decode(response.body) as Map<String, dynamic>;
...