在 Flutter 中,点击卡片列表跳转到详情页,核心是使用 Navigator
组件管理页面跳转。
完整代码(含跳转功能)
Dart
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(primarySwatch: Colors.green),
// 配置路由(管理页面跳转)
initialRoute: '/', // 初始页面
routes: {
'/': (context) => const ChatListPage(), // 列表页
'/detail': (context) => const ChatDetailPage(), // 详情页
},
);
}
}
// 1. 聊天列表页
class ChatListPage extends StatelessWidget {
const ChatListPage({Key? key}) : super(key: key);
// 模拟聊天数据
List<Map<String, dynamic>> getChats() {
return [
{
'id': 1,
'name': '张三',
'avatar': 'https://picsum.photos/100/100?random=1',
'message': '下午一起吃饭吗?',
'time': DateTime.now().subtract(const Duration(minutes: 5)),
},
{
'id': 2,
'name': '李四',
'avatar': 'https://picsum.photos/100/100?random=2',
'message': '好的,我稍后回复你',
'time': DateTime.now().subtract(const Duration(hours: 1)),
},
];
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('微信')),
body: ListView.builder(
itemCount: getChats().length,
itemBuilder: (context, index) {
final chat = getChats()[index];
return ListTile(
leading: CircleAvatar(
backgroundImage: NetworkImage(chat['avatar']),
),
title: Text(chat['name']),
subtitle: Text(chat['message']),
trailing: Text(DateFormat('HH:mm').format(chat['time'])),
// 点击事件:跳转到详情页
onTap: () {
// 传递数据到详情页(通过路由参数)
Navigator.pushNamed(
context,
'/detail',
arguments: chat, // 把当前聊天数据传过去
);
},
);
},
),
);
}
}
// 2. 聊天详情页
class ChatDetailPage extends StatelessWidget {
const ChatDetailPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
// 获取从列表页传递过来的数据
final Map<String, dynamic> chat =
ModalRoute.of(context)?.settings.arguments as Map<String, dynamic>;
return Scaffold(
appBar: AppBar(
title: Text(chat['name']), // 显示聊天对象名称
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('与 ${chat['name']} 的聊天详情'),
const SizedBox(height: 20),
Text('最后一条消息:${chat['message']}'),
// 可以在这里添加更多详情内容(如聊天记录)
],
),
),
);
}
}