Недавно я начал изучать Flutter.
Когда я вставляю ЗАКАЗАТЬ СЕЙЧАС, получаю ошибку:
тип CartItem не является подтипом типа CartItem в приведении типов, где
Когда я нажимаю кнопку ЗАКАЗАТЬ СЕЙЧАС, мне приходится переходить на пустой экран заказа.
Если я не добавлю актерский состав, я получаю сообщение об ошибке The argument type 'List<CartItem>' can't be assigned to the parameter type 'List<CartItem>'
class CartScreen extends StatelessWidget {
static const routeName = '/cart';
const CartScreen({super.key});
@override
Widget build(BuildContext context) {
final cart = Provider.of<Cart>(context);
final orders = Provider.of<Orders>(context);
return Scaffold(
appBar: AppBar(
title: Text(
'Your cart',
style: Theme.of(context).textTheme.bodyLarge,
),
),
body: Column(
children: [
Card(
margin: const EdgeInsets.all(15),
child: Padding(
padding: const EdgeInsets.all(8),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text(
'Total',
style: TextStyle(fontSize: 20),
),
Consumer<Cart>(
builder: (BuildContext context, Cart cart, Widget? widget) {
return Chip(
label: Text(
'\$${cart.totalAmount}',
),
backgroundColor: Colors.white,
);
},
),
ElevatedButton(
onPressed: () {
orders.addOrder(
cart.items.values.cast<CartItem>().toList(),
cart.totalAmount,
);
cart.clear();
},
child: Text(
'ORDER NOW',
style: Theme.of(context).textTheme.bodyMedium,
),
),
],
),
),
),
Expanded(
child: ListView.builder(
itemBuilder: (context, index) => CartItem(
id: cart.items.values.toList()[index].id,
productId: cart.items.keys.toList()[index],
title: cart.items.values.toList()[index].title,
quantity: cart.items.values.toList()[index].quantity,
price: cart.items.values.toList()[index].price,
),
itemCount: cart.itemCount,
),
),
],
),
);
}
}
заказы
class OrderItem {
final String id;
final double amount;
final List<CartItem> products;
final DateTime dateTime;
const OrderItem({
required this.id,
required this.amount,
required this.products,
required this.dateTime,
});
}
class Orders with ChangeNotifier {
final List<OrderItem> _orders = [];
List<OrderItem> get orders {
return [..._orders];
}
void addOrder(
List<CartItem> cartProducts,
double total,
) {
_orders.insert(
0,
OrderItem(
id: DateTime.now().toString(),
amount: total,
products: cartProducts,
dateTime: DateTime.now(),
),
);
notifyListeners();
}
}
тележка
class CartItem {
final String id;
final String title;
final int quantity;
final double price;
CartItem({
required this.id,
required this.title,
required this.quantity,
required this.price,
});
}
class Cart with ChangeNotifier {
late Map<String, CartItem> _items = {};
Map<String, CartItem> get items {
return {..._items};
}
int get itemCount {
return _items.length;
}
double get totalAmount {
double total = 0.0;
_items.forEach((key, cartItem) {
total += cartItem.price * cartItem.quantity;
});
return total;
}
void addItem(
String productId,
double price,
String title,
) {
if (_items.containsKey(productId)) {
_items.update(
productId,
(existingCartItem) => CartItem(
id: existingCartItem.id,
title: existingCartItem.title,
quantity: existingCartItem.quantity + 1,
price: existingCartItem.price,
),
);
} else {
_items.putIfAbsent(
productId,
() => CartItem(
id: DateTime.now().toString(),
title: title,
quantity: 1,
price: price,
),
);
}
notifyListeners();
}
void removeItem(String productId) {
_items.remove(productId);
notifyListeners();
}
void clear() {
_items = {};
notifyListeners();
}
}
Не могу сказать, ваша ли это проблема, так как вы не показываете свои import
и не указываете, какая у вас машина разработки. Но если вы используете файловую систему, нечувствительную к регистру, я бы сначала проверил все ваши import
и убедился, что все они используют одинаковую капитализацию.
Я думаю, что проблема в том, что у вас есть класс CartItem, который представляет вашу модель данных, и еще один CartItem, который является виджетом, вызывающим prblm.
Класс модели данных CarItem.
class CartItem {
final String id;
final String title;
final int quantity;
final double price;
CartItem({
required this.id,
required this.title,
required this.quantity,
required this.price,
});
}
Другое — это виджет CartItem, потому что вы возвращаете его внутри списка.
Expanded(
child: ListView.builder(
itemBuilder: (context, index) => CartItem(
id: cart.items.values.toList()[index].id,
productId: cart.items.keys.toList()[index],
title: cart.items.values.toList()[index].title,
quantity: cart.items.values.toList()[index].quantity,
price: cart.items.values.toList()[index].price,
),
itemCount: cart.itemCount,
),
),
Поскольку один из них — виджет, а другой — объект, отображается ошибка типа.
Когда вы получаете ошибку, например
type 'Foo' is not a subtype of type 'Foo'
, это означает, что у вас есть два класса с одинаковым именем (в данном случае два класса с именемCartItem
). Очень частая причина этого заключается в том, что вы используете файловую систему, нечувствительную к регистру, и импортируете один и тот же файл.dart
с непоследовательной заглавной буквой пути к файлу. Например, если у вас есть что-то вродеimport 'cartItem.dart';
иimport 'cartitem.dart';
, они будут рассматриваться как два отдельных импорта с двумя разными классами, оба с именемCartItem
.