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

Flutter技术咨询:点击ListView列表项跳转至详情页实现方案

Flutter实现ListView点击跳转详情页

步骤1:创建详情页面组件

先编写一个专门展示课程详情的页面,它接收选中的课程数据作为参数,将所有信息逐一展示:

class CourseDetailPage extends StatelessWidget {
  final Map<String, dynamic> course;

  const CourseDetailPage({super.key, required this.course});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(course['name']),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Image.asset("assets/images/${course['logo']}.png"),
            const SizedBox(height: 16),
            Text("课程名称: ${course['name']}", style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
            const SizedBox(height: 8),
            Text("日期: ${course['date']}"),
            const SizedBox(height: 8),
            Text("距离: ${course['distance']} 米"),
            const SizedBox(height: 8),
            Text("时长: ${Duration(seconds: course['temps']).toString().split('.').first}"),
          ],
        ),
      ),
    );
  }
}

步骤2:修改ListView的点击事件

替换InkWell的onTap逻辑,使用Navigator.push打开详情页,同时将当前选中的course对象传递过去:

@override
Widget build(BuildContext context) {
  return Center(
    child: ListView.builder(
      itemCount: courses.length,
      itemBuilder: (context, index) {
        final course = courses[index];
        final logo = course['logo'];
        final name = course['name'];
        final date = course['date'];

        return InkWell(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => CourseDetailPage(course: course),
              ),
            );
          },
          child: Card(
            child: ListTile(
              leading: Image.asset("assets/images/$logo.png"),
              title: Text('$name'),
              subtitle: Text('course du $date'),
              trailing: const Icon(Icons.more_vert),
            ),
          ),
        );
      },
    ),
  );
}

可选优化建议

如果后续条目数量增多,建议将Map改为自定义类,提升代码类型安全性和可维护性:

class Course {
  final String name;
  final String date;
  final String logo;
  final int distance;
  final int temps;

  Course({
    required this.name,
    required this.date,
    required this.logo,
    required this.distance,
    required this.temps,
  });
}

之后将courses数组改为List<Course>类型即可。

内容的提问来源于stack exchange,提问作者Kach

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 13:50:33