You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter实现列表页跳转商品详情页并传递对应商品数据

解决Flutter列表页跳转详情页无数据问题

问题核心是跳转时未将选中的商品数据传递给详情页,以下是具体修复步骤:

1. 改造详情页(ProductDetails),接收商品参数

修改product_detail.dart,让页面接收Product类型参数,并基于该参数渲染详情内容:

import 'package:flutter/material.dart';
import 'package:flutter_get_api/model.dart';

class ProductDetails extends StatelessWidget {
  // 声明要接收的商品数据
  final Product product;

  // 构造函数强制要求传入商品参数
  const ProductDetails({Key? key, required this.product}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Color.fromARGB(255, 32, 28, 80),
        title: Text(product.title ?? '商品详情'),
      ),
      backgroundColor: Colors.white,
      body: SingleChildScrollView(
        padding: EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Image.network(product.thumbnail ?? ''),
            SizedBox(height: 16),
            Text(
              product.title ?? '',
              style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 8),
            Text(
              product.brand ?? '',
              style: TextStyle(fontSize: 18, color: Colors.grey[600]),
            ),
            SizedBox(height: 16),
            Text(product.description ?? ''),
            SizedBox(height: 24),
            Text(
              '\$${product.price ?? 0}',
              style: TextStyle(fontSize: 22, color: Colors.green, fontWeight: FontWeight.bold),
            ),
          ],
        ),
      ),
    );
  }
}

2. 列表页跳转时传递选中的商品

在列表页的GestureDetector点击回调中,把当前索引对应的商品对象传递给详情页:

// 修改原代码中的onTap逻辑
onTap: () {
  Navigator.push(
    context,
    MaterialPageRoute(
      builder: (context) => ProductDetails(
        product: snapshot.data!.products![index],
      ),
    ),
  );
},

3. 优化API请求避免重复调用

原代码每次页面重建都会重新发起API请求,可将Future对象提前初始化,只执行一次请求:

class _DetailsState extends State<Details> {
  // 提前声明Future变量
  late Future<Model> _productsFuture;

  @override
  void initState() {
    super.initState();
    // 在页面初始化时发起API请求
    _productsFuture = getProductsApi();
  }

  Future<Model> getProductsApi() async {
    // 修正拼写错误:responce → response
    final response = await http.get(Uri.parse('https://dummyjson.com/products'));
    var data = jsonDecode(response.body.toString());
    if (response.statusCode == 200) {
      return Model.fromJson(data);
    } else {
      // 错误时抛出异常,方便FutureBuilder处理错误状态
      throw Exception('加载商品失败');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // ... 原有页面结构不变
      body: Column(
        children: [
          Expanded(
              child: FutureBuilder<Model>(
            // 使用提前初始化的Future对象
            future: _productsFuture,
            builder: (context, snapshot) {
              // ... 原有builder逻辑不变
            },
          )),
        ],
      ),
    );
  }
}

额外修复点

  • 修正了API请求方法中的拼写错误:responce改为response
  • 错误状态下抛出异常,便于在FutureBuilder中添加错误提示(比如snapshot.hasError时显示错误文本)

内容的提问来源于stack exchange,提问作者Rana sharjeel Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 21:55:44