ar_tourism_flutter_unity/lib/pages/message/guanZhu.dart
2025-05-14 17:04:13 +08:00

331 lines
9.5 KiB
Dart

import 'package:flutter/material.dart';
import '../../apis/app.dart';
import '../../components/appbar.dart';
import '../../components/emptyState.dart';
class GuanZhuPage extends StatefulWidget {
// 修改为 StatefulWidget
@override
_GuanZhuPageState createState() => _GuanZhuPageState();
}
class _GuanZhuPageState extends State<GuanZhuPage> {
List<dynamic> guanZhuList = []; // 确保初始化列表
bool isLoading = false;
int currentPage = 1;
int totalCount = 0;
final int pageSize = 10;
final ScrollController _scrollController = ScrollController();
@override
void initState() {
super.initState();
getNewLikeList();
_scrollController.addListener(_onScroll);
}
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
void _onScroll() {
if (_scrollController.position.pixels ==
_scrollController.position.maxScrollExtent) {
_loadMore();
}
}
Future<void> _loadMore() async {
if (!isLoading && guanZhuList.length < totalCount) {
await getNewLikeList();
}
}
// 获取新增关注人数接口
getNewLikeList() async {
if (isLoading) return;
setState(() {
isLoading = true;
});
try {
final res = await userApi.getNewFollowList(
page: currentPage,
pageSize: pageSize,
);
if (res['code'] == 200) {
final newItems = res['rows'] as List;
setState(() {
if (currentPage == 1) {
guanZhuList = newItems;
} else {
guanZhuList.addAll(newItems);
}
totalCount = res['total'] ?? 0;
currentPage++;
isLoading = false;
});
}
} catch (error) {
print("网络错误: $error");
setState(() {
isLoading = false;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: CustomAppBar(
title: '新增关注',
onBackPressed: () {
Navigator.pop(context, true);
},
),
body: Container(
decoration: const BoxDecoration(color: Color(0xff0C0C16)),
child: RefreshIndicator(
onRefresh: () async {
currentPage = 1;
await getNewLikeList();
},
child: guanZhuList.isEmpty && !isLoading
? const EmptyState(message: '暂无关注用户')
: ListView.builder(
controller: _scrollController,
padding: const EdgeInsets.symmetric(vertical: 12),
// 设置项目之间的间距
itemCount: guanZhuList.length + 1,
itemBuilder: (context, index) {
if (index == guanZhuList.length) {
return Container(
padding: const EdgeInsets.symmetric(vertical: 16),
alignment: Alignment.center,
child: guanZhuList.length < totalCount
? const SizedBox(
width: 24,
height: 24,
child: CircularProgressIndicator(
strokeWidth: 2.0,
color: Colors.white,
),
)
: const Text(
'已经到底啦',
style: TextStyle(
color: Colors.grey,
fontSize: 14,
),
),
);
}
return _buildGuanZhuItem(guanZhuList[index]);
},
),
),
),
);
}
Widget _buildGuanZhuItem(Map<String, dynamic> user) {
// 获取关注状态
final followStatus = user['followStatus']?.toString() ?? '0';
return ListTile(
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 8,
),
leading: GestureDetector(
onTap: () => _navigateToUserProfile(user),
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Image.network(
user['avatar'] ?? '',
width: 50,
height: 50,
fit: BoxFit.cover,
errorBuilder: (context, error, stackTrace) {
return Container(
width: 50,
height: 50,
color: Colors.grey[300],
child: const Icon(Icons.person, color: Colors.grey),
);
},
),
),
),
title: GestureDetector(
onTap: () => _navigateToUserProfile(user),
child: Text(
user['nickName'] ?? '未知用户',
style: const TextStyle(fontSize: 16, color: Color(0xffF5F5F5)),
),
),
subtitle: Text(
user['detail'] ?? '',
style: const TextStyle(fontSize: 12, color: Color(0xff6D717A)),
),
trailing: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.transparent,
elevation: 0,
shape: RoundedRectangleBorder(
borderRadius: const BorderRadius.all(Radius.circular(50)),
side: BorderSide(
color: followStatus == "1" ? const Color(0xff464952) : Colors.red,
width: 1.5,
),
),
minimumSize: const Size(70, 26),
padding: const EdgeInsets.all(0),
),
onPressed: () => _handleFollowAction(user),
child: Text(
_getFollowButtonText(followStatus),
style: TextStyle(
color: followStatus == "1" ? const Color(0xff6D717A) : Colors.red,
fontSize: 12,
),
),
),
);
}
// 获取关注按钮显示的文本
String _getFollowButtonText(String followStatus) {
switch (followStatus) {
case "0":
return "回关";
case "1":
return "互相关注";
default:
return "回关";
}
}
// 处理关注/取消关注操作
Future<void> _handleFollowAction(Map<String, dynamic> user) async {
final followStatus = user['followStatus']?.toString() ?? '0';
if (followStatus == "1") {
// 如果已经是互相关注,显示确认取消关注的对话框
final bool? shouldUnfollow = await showDialog<bool>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
backgroundColor: const Color(0xFF1F1F1F),
title: const Text(
'确认不再关注?',
style: TextStyle(color: Colors.white),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: const Text(
'取消',
style: TextStyle(color: Color(0xff6D717A)),
),
),
TextButton(
onPressed: () => Navigator.of(context).pop(true),
child: const Text(
'确认',
style: TextStyle(color: Colors.red),
),
),
],
);
},
);
if (shouldUnfollow == true) {
await _unfollowUser(user);
}
} else {
// 如果未关注,直接执行关注操作
await _followUser(user);
}
}
// 关注用户
Future<void> _followUser(Map<String, dynamic> user) async {
try {
final response = await userApi.addFollow(user['userId'].toString());
if (response['code'] == 200) {
setState(() {
user['followStatus'] = "1";
});
} else {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(response['msg'] ?? '关注失败')),
);
}
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('网络请求失败')),
);
}
}
}
// 取消关注用户
Future<void> _unfollowUser(Map<String, dynamic> user) async {
try {
final response = await userApi.cancelFollow(user['userId'].toString());
if (response['code'] == 200) {
setState(() {
user['followStatus'] = "0";
});
} else {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(response['msg'] ?? '取消关注失败')),
);
}
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('网络请求失败')),
);
}
}
}
// 跳转到用户个人主页
void _navigateToUserProfile(Map<String, dynamic> user) {
Navigator.pushNamed(
context,
'/otherMine',
arguments: {
'userId': user['userId'],
'nickName': user['nickName'] ?? '未知用户',
'avatar': user['avatar'] ?? '',
'isFollow': user['followStatus'] ?? '0',
},
).then((result) {
if (result != null && result is Map<String, dynamic>) {
setState(() {
// 更新列表中对应用户的关注状态
final index = guanZhuList.indexWhere(
(item) => item['userId'] == result['userId']);
if (index != -1) {
guanZhuList[index]['followStatus'] = result['isFollowed'] ? "1" : "0";
}
});
}
});
}
}