Home > front end >  Unhandled Exception: type 'String' is not a subtype of type 'List<dynamic>'
Unhandled Exception: type 'String' is not a subtype of type 'List<dynamic>'

Time:03-28

Here are the codes that i need description

Future<void> fetchAndSetOrders() async {

  const _myUrl =
      'https://shop-960ca-default-rtdb.firebaseio.com/OrderContainer.json';

  final response = await http.get(Uri.parse(_myUrl));
  final extractedData = json.decode(response.body) as Map<String, dynamic>;

  List<OrderModel> orderFromServer = [];

  extractedData.forEach((key, value) {

    print(value['orderList']);

    orderFromServer.add(OrderModel(
      dateTime: DateTime.parse(value['dateTime']),
      orderCost: value['orderCost'],
      orderedId: key,

      orderedList: (value['orderList'] as List<dynamic>)
          .map((e) => CartIModel(
                cartId: e['cartId'],
                cartPrice: e['cartPrice'],
                cartTitle: e['cartTitle'],
                cartQuantity: e['cartQuantity'],
              ))
          .toList(),
    ));
  });

  _items = orderFromServer.reversed.toList();

  notifyListeners();
}

Print result:

({cartId: 2022-03-26 00:33:44.960313, cartTitle: Programmer, cartPrice: 56.0, cartQuantity: 1}, {cartId: 2022-03-26 00:33:46.964685, cartTitle: zoom5, cartPrice: 345.0, cartQuantity: 1})

CodePudding user response:

From the JSON example you provided , it appears that orderList is a string not a list

"({cartId: 2022-03-26 00:33:44.960313, cartTitle: Programmer, cartPrice: 56.0, cartQuantity: 1}, {cartId: 2022-03-26 00:33:46.964685, cartTitle: zoom5, cartPrice: 345.0, cartQuantity: 1})"

So this can't be parsed as a list

CodePudding user response:

Your data structure is:

{
  "-Mz2--RzkrXgbGHA2pga" : {
    "dateTime" : "2022-03-26T00:33:51.488931",
    "orderCost" : 401.0,
    "orderList" : "({cartId: 2022-03-26 00:33:44.960313, cartTitle: Programmer, cartPrice: 56.0, cartQuantity: 1}, {cartId: 2022-03-26 00:33:46.964685, cartTitle: zoom5, cartPrice: 345.0, cartQuantity: 1})"
  }
}

So what you call orderList is actually a string, not a JSON object. To further decode that string, you can use:

json.decode(value['orderList'] as String)
  • Related