好的,我可以帮助您实现这个功能。首先,我们需要创建一个新的页面来显示商品的详细信息。我将其称为 ProductDetailPage。您可以按照以下步骤操作:

  1. 在 pages 文件夹中创建一个名为 product_detail_page.dart 的新文件。
  2. 在该文件中,导入所需的包:
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';

import '../models/product.dart';
import '../services/api_service.dart';
  1. 创建一个名为 ProductDetailPage 的类,它应该是 StatefulWidget。在此类中,我们需要从主页中获取所选商品的 ID,并使用 API 服务获取商品详细信息。我们还需要在页面上显示商品的详细信息。
class ProductDetailPage extends StatefulWidget {
  final int productId;

  ProductDetailPage({required this.productId});

  @override
  _ProductDetailPageState createState() =>
      _ProductDetailPageState(productId: productId);
}

class _ProductDetailPageState extends State<ProductDetailPage> {
  final int productId;
  late Future<Product> _productFuture;

  _ProductDetailPageState({required this.productId});

  @override
  void initState() {
    super.initState();
    _productFuture = ApiService.getProductDetail(productId);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('商品详情'),
      ),
      body: FutureBuilder<Product>(
        future: _productFuture,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return _buildProductDetail(snapshot.data!);
          } else if (snapshot.hasError) {
            return Center(
              child: Text('加载商品详情失败'),
            );
          }
          return Center(
            child: CircularProgressIndicator(),
          );
        },
      ),
    );
  }

  Widget _buildProductDetail(Product product) {
    return SingleChildScrollView(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          CachedNetworkImage(
            imageUrl: product.imageUrl,
            fit: BoxFit.cover,
            errorWidget: (context, url, error) => Icon(Icons.error),
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  product.name,
                  style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
                ),
                SizedBox(height: 8),
                Text(
                  '价格: ¥${product.price.toStringAsFixed(2)}',
                  style: TextStyle(fontSize: 18),
                ),
                SizedBox(height: 8),
                Text(
                  '品牌: ${product.brand}',
                  style: TextStyle(fontSize: 18),
                ),
                SizedBox(height: 8),
                Text(
                  '描述: ${product.description}',
                  style: TextStyle(fontSize: 18),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
  1. 现在我们需要在主页中为每个商品添加一个可点击的卡片。当用户点击该卡片时,我们将导航到 ProductDetailPage 并向其传递所选商品的 ID。我们还需要为卡片添加一个缩放动画。
class _HomePageState extends State<HomePage> with SingleTickerProviderStateMixin {
  AnimationController? _animationController;
  Animation<double>? _animation;

  @override
  void initState() {
    super.initState();
    _loadProducts();

    _animationController = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 300),
    );

    _animation = Tween<double>(begin: 1, end: 0.95).animate(
      CurvedAnimation(
        parent: _animationController!,
        curve: Curves.easeInOut,
      ),
    );
  }

  @override
  void dispose() {
    _animationController!.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('商城主页')),
      body: SmartRefresher(
        enablePullDown: false,
        enablePullUp: true,
        controller: _refreshController,
        onLoading: _onLoading,
        child: GridView.builder(
          itemCount: _products.length,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            childAspectRatio: 0.75,
          ),
          itemBuilder: (BuildContext context, int index) {
            final product = _products[index];
            return GestureDetector(
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) =>
                        ProductDetailPage(productId: product.id),
                  ),
                );
              },
              child: ScaleTransition(
                scale: _animation!,
                child: Card(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Expanded(
                        child: CachedNetworkImage(
                          imageUrl: product.imageUrl,
                          fit: BoxFit.cover,
                          errorWidget: (context, url, error) =>
                              Icon(Icons.error),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.all(8),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Text(product.name,
                                style: TextStyle(fontWeight: FontWeight.bold)),
                            SizedBox(height: 4),
                            Text('价格: ¥${product.price.toStringAsFixed(2)}'),
                            SizedBox(height: 4),
                            Text('品牌: ${product.brand}'),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            );
          },
        ),
      ),
    );
  }
}
  1. 最后,我们需要在 ApiService 中添加一个方法来获取商品的详细信息。
static Future<Product> getProductDetail(int productId) async {
  try {
    Response response = await _dio.get(
      '$baseUrl/getproductdetail',
      queryParameters: {
        'productId': productId,
      },
    );
    dynamic jsonData = jsonDecode(response.data);
    Product product = Product.fromJson(jsonData);
    return product;
  } catch (e) {
    throw e;
  }
}

现在您应该可以点击主页上的任何商品并跳转到其详细信息页面了。如果您需要帮助,请告诉我。

添加购物车功能:

  1. 在 ProductDetailPage 中添加一个按钮,用于将商品添加到购物车。
  2. 创建一个 Cart 类来存储购物车中的商品。
  3. 创建一个 CartService 类来管理购物车,例如添加商品、删除商品、获取购物车信息等。
  4. 在 ProductDetailPage 的按钮点击事件中,调用 CartService 的添加商品方法,并将添加成功后的提示信息显示给用户。

UI 优化:

您可以使用 Flutter 的 Theme 和 Widget 来创建更漂亮的 UI。例如,您可以使用 ElevatedButton 创建一个带有圆角和阴影的按钮,使用 Container 设置背景颜色,使用 Padding 和 SizedBox 控制布局,使用 TextStyle 设置文字样式等等。

注意:

  • 这只是一个基本的实现示例,您可以根据您的实际需求进行修改。
  • 记得在 pubspec.yaml 文件中添加所需的包,例如 cached_network_image、dio 等。
  • 在使用 API 服务时,请确保您的 API 接口是正确的,并且您已经正确配置了 API 密钥。
Flutter 商城:实现商品点击跳转到详情页面,包含缩放动画和购物车功能