import 'package:cached_network_image/cached_network_image.dart'; import 'package:dating_touchme_app/model/live/gift_product_model.dart'; import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; class LiveRoomGiftItem extends StatefulWidget { final dynamic item; // 支持 Map 或 GiftProductModel final int active; final int index; final void Function(int) changeActive; const LiveRoomGiftItem({ super.key, required this.item, required this.active, required this.index, required this.changeActive, }); @override State createState() => _LiveRoomGiftItemState(); } class _LiveRoomGiftItemState extends State { // 判断是否为 GiftProductModel bool get _isGiftProductModel => widget.item is GiftProductModel; // 获取图片 Widget _buildImage() { if (_isGiftProductModel) { final gift = widget.item as GiftProductModel; if (gift.mainPic.isNotEmpty) { return CachedNetworkImage( imageUrl: gift.mainPic, width: 41.w, height: 41.w, fit: BoxFit.cover, placeholder: (context, url) => Container( width: 41.w, height: 41.w, color: Colors.grey[300], child: Center( child: SizedBox( width: 20.w, height: 20.w, child: CircularProgressIndicator( strokeWidth: 2, color: Colors.grey[600], ), ), ), ), errorWidget: (context, url, error) => Container( width: 41.w, height: 41.w, color: Colors.grey[300], child: Icon(Icons.error_outline, size: 20.w, color: Colors.grey), ), ); } else { return Container( width: 41.w, height: 41.w, color: Colors.grey[300], ); } } else { final map = widget.item as Map; final icon = map["icon"] as String?; if (icon != null && icon.isNotEmpty) { return Image.asset(icon, width: 41.w, height: 41.w); } else { return Container( width: 41.w, height: 41.w, color: Colors.grey[300], ); } } } // 获取标题 String _getTitle() { if (_isGiftProductModel) { return (widget.item as GiftProductModel).productTitle; } else { return (widget.item as Map)["title"]?.toString() ?? ''; } } // 获取价格 String _getPrice() { if (_isGiftProductModel) { final price = (widget.item as GiftProductModel).unitSellingPrice; return "${price.toInt()}支"; } else { final price = (widget.item as Map)["price"]; return "${price ?? 0}支"; } } @override Widget build(BuildContext context) { return InkWell( onTap: () { widget.changeActive(widget.index); }, child: Container( width: 83.w, height: 94.w, padding: EdgeInsets.only(top: 10.w), decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(9.w)), color: Color.fromRGBO( 117, 98, 249, widget.active == widget.index ? .2 : 0, ), border: Border.all( width: 1, color: Color.fromRGBO( 117, 98, 249, widget.active == widget.index ? 1 : 0, ), ), ), child: Column( children: [ _buildImage(), SizedBox(height: 7.w), Text( _getTitle(), style: TextStyle(fontSize: 11.w, color: Colors.white), maxLines: 1, overflow: TextOverflow.ellipsis, ), SizedBox(height: 1.w), Text( _getPrice(), style: TextStyle( fontSize: 7.w, color: const Color.fromRGBO(144, 144, 144, 1), ), ), ], ), ), ); } }