我在此代码块中收到一个错误,显示"_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();
}
}
3条答案
按热度按时间2hh7jdfx1#
未来获取和设置订单()异步{
}
未来addOrder(列出购物车产品,双倍总计)异步{
}}
erhoui1w2#
您可以考虑添加,
types
显式如下所示:zbsbpyhn3#
添加到字符串()