Flutter/Dart _TypeError(类型“String”不是“index”的类型“int”的子类型)

vaj7vani  于 2023-03-09  发布在  Flutter
关注(0)|答案(3)|浏览(150)

我在此代码块中收到一个错误,显示"_TypeError(type 'String' is not a subtype of type 'int' of 'index')"。当我转到应用的订单页面时发生错误。它在amount:datetime:上显示错误。当我在购物车结账时,它会将购物车发送到数据库,但是,当我转到订单页面时,错误发生。

extractedData.forEach((orderId, orderData) {
      loadedOrders.add(
        OrderItem(
          id: orderId,
          amount: orderData['amount'],
          dateTime: DateTime.parse(orderData['dateTime']),
          products: (orderData['products'] as List<dynamic>)
              .map(
                (item) => CartItem(
                  id: item['id'],
                  title: item['title'],
                  quantity: item['quantity'],
                  price: item['price'],
                ),
              )
              .toList(),

这是我的数据库:

shopapp-6740d-default-rtdb:
       orders: -MpxLeVE1f5xosVHiYdM
                 amount: 59.99
                 dateTime: "2021-12-02T17:53:52.689091"
                 products: 0
                      id: "2021-12-02 17:53:50.251572"
                      price: 59.99
                      quantity: 1
                      title: "Trousers"

这是我的全部代码。

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

import './cart.dart';

class OrderItem {
  final String id;
  final double amount;
  final List<CartItem> products;
  final DateTime dateTime;

  OrderItem({
    required this.id,
    required this.amount,
    required this.products,
    required this.dateTime,
  });
}

class Orders with ChangeNotifier {
  List<OrderItem> _orders = [];

  List<OrderItem> get orders {
    return [..._orders];
  }

  Future<void> fetchAndSetOrders() async {
    const url = 'https://shopapp-6740d-default-rtdb.firebaseio.com/orders.json';

    final response = await http.post(Uri.parse(url));
    final List<OrderItem> loadedOrders = [];
    final extractedData = json.decode(response.body) as Map<String, dynamic>;

    if(extractedData == null){
      return;
    }

    extractedData.forEach((orderId, orderData) {
      loadedOrders.add(
        OrderItem(
          id: orderId,
          amount: orderData['amount'],
          dateTime: DateTime.parse(orderData['dateTime']),
          products: (orderData['products'] as List<dynamic>)
              .map(
                (item) => CartItem(
                  id: item['id'],
                  title: item['title'],
                  quantity: item['quantity'],
                  price: item['price'],
                ),
              )
              .toList(),
        ),
      );
    });
    _orders = loadedOrders.reversed.toList();
    notifyListeners();
  }

  Future<void> addOrder(List<CartItem> cartProducts, double total) async {
    const url = 'https://shopapp-6740d-default-rtdb.firebaseio.com/orders.json';
    final timestamp = DateTime.now();
    final response = await http.post(
      Uri.parse(url),
      body: json.encode({
        'amount': total,
        'dateTime': DateTime.now().toIso8601String(),
        'products': cartProducts
            .map((cp) => {
                  'id': cp.id,
                  'title': cp.title,
                  'quantity': cp.quantity,
                  'price': cp.price,
                })
            .toList(),
      }),
    );

    _orders.insert(
      0,
      OrderItem(
        id: json.decode(response.body)['name'],
        amount: total,
        products: cartProducts,
        dateTime: DateTime.now(),
      ),
    );
    notifyListeners();
  }
}
2hh7jdfx

2hh7jdfx1#

未来获取和设置订单()异步{

const url = 'https://shopapp-6740d-default-rtdb.firebaseio.com/orders.json';  //change const to final

final response = await http.get(Uri.parse(url)); //changes
final List<OrderItem> loadedOrders = [];
final extractedData = json.decode(response.body) as Map<String, dynamic>;

if(extractedData == null){
  return;
}

extractedData.forEach((orderId, orderData) {
  loadedOrders.add(
    OrderItem(
      id: orderId,
      amount: orderData['amount'],
      dateTime: DateTime.parse(orderData['dateTime']),
      products: (orderData['products'] as List<dynamic>)
          .map(
            (item) => CartItem(
              id: item['id'],
              title: item['title'],
              quantity: item['quantity'],
              price: item['price'],
            ),
          )
          .toList(),
    ),
  );
});
_orders = loadedOrders.reversed.toList();
notifyListeners();

}
未来addOrder(列出购物车产品,双倍总计)异步{

const url = 'https://shopapp-6740d-default-rtdb.firebaseio.com/orders.json';  //change const to final
final timeStamp = DateTime.now();    //chnages
final response = await http.post(
  Uri.parse(url),
  body: json.encode({
    'amount': total,
    'dateTime': timeStamp.toIso8601String(),  //changes
    'products': cartProducts
        .map((cp) => {
              'id': cp.id,
              'title': cp.title,
              'quantity': cp.quantity,
              'price': cp.price,
            })
        .toList(),
  }),
);

_orders.insert(
  0,
  OrderItem(
    id: json.decode(response.body)['name'],
    amount: total,
    products: cartProducts,
    dateTime: timeStamp,        //changes
  ),
);
notifyListeners();

}}

erhoui1w

erhoui1w2#

您可以考虑添加,types显式如下所示:

amount: orderData['amount'] as String,
dateTime: DateTime.parse(orderData['dateTime']) as DateTime
zbsbpyhn

zbsbpyhn3#

添加到字符串()

extractedData.forEach((orderId, orderData) {
          loadedOrders.add(
            OrderItem(
              id: orderId,
              amount: orderData['amount'],
              dateTime: DateTime.parse(orderData['dateTime']),
              products: (orderData['products'] as List<dynamic>)
                  .map(
                    (item) => CartItem(
                      id: item['id'].toString(),
                      title: item['title'].toString(),
                      quantity: item['quantity'].toString(),
                      price: item['price'].toString(),
                    ),
                  )
                  .toList(),

相关问题