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

606 lines
23 KiB
Dart

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:provider/provider.dart';
import '../../apis/app.dart';
import '../../components/workGrid.dart';
import '../../providers/auth_provider.dart';
import '../mine/mine.dart';
class OtherMinePage extends StatefulWidget {
final Map<String, dynamic> work;
const OtherMinePage({super.key, required this.work});
@override
State<OtherMinePage> createState() => _OtherMinePageState();
}
class _OtherMinePageState extends State<OtherMinePage> {
List<WorkItem> publishList = [];
bool isLoading = true;
Map<String, dynamic> userDetail = {};
int total = 0;
bool _isFollowed = false;
bool _isOwnWork = false;
// 分页相关变量
int _currentPage = 1;
static const int _pageSize = 10;
bool _hasMore = true;
bool _isLoadingMore = false;
final ScrollController _scrollController = ScrollController();
@override
void initState() {
super.initState();
_checkIfOwnWork();
_fetchUserDetail();
_fetchPublishData();
_scrollController.addListener(_onScroll);
}
Future<void> _checkIfOwnWork() async {
try {
final authProvider = Provider.of<AuthProvider>(context, listen: false);
final currentUserId = authProvider.userId;
setState(() {
_isOwnWork =
currentUserId.toString() == widget.work['userId'].toString();
});
} catch (e) {
print('检查作品所有权时出错: $e');
setState(() {
_isOwnWork = false;
});
}
}
// 添加方法来更新关注状态
void _updateFollowStatus(bool isFollowed) {
if (mounted) {
setState(() {
_isFollowed = isFollowed;
if (userDetail.isNotEmpty) {
userDetail['isFollow'] = isFollowed ? "1" : "0";
}
});
}
}
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
void _onScroll() {
if (_scrollController.position.pixels >=
_scrollController.position.maxScrollExtent - 200) {
_loadMore();
}
}
Future<void> _fetchUserDetail() async {
try {
final response =
await userApi.getOtherPublish(widget.work['userId'].toString());
if (response['code'] == 200) {
if (mounted) {
setState(() {
userDetail = response['data'];
print("用户信息: $userDetail");
// 从接口返回数据中获取关注状态
_isFollowed = userDetail['isFollow'] == "1";
});
}
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('获取用户信息失败: $e')),
);
}
}
}
Future<void> _fetchPublishData() async {
try {
final data = await userApi.othersPublishDetail(
widget.work['userId'].toString(),
page: 1,
pageSize: _pageSize,
);
print("获取发布列表数据: $data"); // 添加日志
if (data['code'] == 200) {
final List rows = data['rows'] as List? ?? [];
setState(() {
total = data['total'] ?? 0;
publishList = rows.map((item) {
print("单个作品数据: $item"); // 添加日志
return WorkItem(
workId: item['workId'] ?? '',
imageUrl: item['workAddress'] ?? '',
title: item['workName'] ?? '',
count: (item['receiveRockets'] ?? 0).toString(),
isAddLike: item['isAddLike'] ?? "0",
);
}).toList();
print("转换后的publishList: ${publishList.map((item) => {
'workId': item.workId,
'count': item.count,
'isAddLike': item.isAddLike,
}).toList()}"); // 添加日志
_hasMore = rows.length >= _pageSize;
isLoading = false;
});
}
} catch (e) {
print("获取发布列表失败: $e"); // 添加日志
setState(() {
isLoading = false;
});
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('加载失败: $e')),
);
}
}
}
Future<void> _loadMore() async {
if (!_hasMore || _isLoadingMore || isLoading) return;
setState(() {
_isLoadingMore = true;
});
try {
final data = await userApi.othersPublishDetail(
widget.work['userId'].toString(),
page: _currentPage + 1,
pageSize: _pageSize,
);
if (data['code'] == 200) {
final List rows = data['rows'] as List? ?? [];
final newItems = rows
.map((item) => WorkItem(
workId: item['workId'] ?? '',
imageUrl: item['workAddress'] ?? '',
title: item['workName'] ?? '',
count: (item['receiveRockets'] ?? 0).toString(),
isAddLike: item['isAddLike'] ?? "0",
))
.toList();
if (mounted) {
setState(() {
publishList.addAll(newItems);
_currentPage++;
_hasMore = rows.length >= _pageSize;
_isLoadingMore = false;
});
}
}
} catch (e) {
if (mounted) {
setState(() {
_isLoadingMore = false;
});
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('加载更多失败: $e')),
);
}
}
}
Future<void> _toggleFollow() async {
if (userDetail['userId'] == null) return;
try {
final previousState = _isFollowed;
setState(() {
_isFollowed = !_isFollowed;
// 同时更新userDetail中的状态
userDetail['isFollow'] = _isFollowed ? "1" : "0";
});
final result = _isFollowed
? await userApi.addFollow(userDetail['userId'])
: await userApi.cancelFollow(userDetail['userId']);
if (result['code'] != 200) {
setState(() {
_isFollowed = previousState;
// 同时更新userDetail中的状态
userDetail['isFollow'] = _isFollowed ? "1" : "0";
});
if (!mounted) return;
showDialog(
context: context,
builder: (context) => AlertDialog(
content: SelectableText.rich(
TextSpan(
text: result['msg'] ?? '操作失败',
style: const TextStyle(color: Colors.red),
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('确定'),
),
],
),
);
}
} catch (e) {
setState(() {
_isFollowed = !_isFollowed;
// 同时更新userDetail中的状态
userDetail['isFollow'] = _isFollowed ? "1" : "0";
});
if (!mounted) return;
showDialog(
context: context,
builder: (context) => AlertDialog(
content: const SelectableText.rich(
TextSpan(
text: '网络请求失败',
style: TextStyle(color: Colors.red),
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('确定'),
),
],
),
);
}
}
@override
Widget build(BuildContext context) {
return PopScope(
canPop: false,
onPopInvoked: (didPop) {
if (didPop) return;
Navigator.pop(context, {
'isFollowed': _isFollowed,
'userId': widget.work['userId'],
});
},
child: Scaffold(
body: Container(
width: double.infinity,
color: const Color(0xff0C0C16),
child: Stack(
children: [
// 顶部背景图
Positioned(
top: 0,
left: 0,
right: 0,
child: Container(
width: MediaQuery.of(context).size.width,
height: 230,
child: Stack(
fit: StackFit.expand,
children: [
// 背景图
userDetail['backGround'] == null
? Container(
color: const Color(0xFF1F212E),
)
: Image.network(
userDetail['backGround']!,
fit: BoxFit.cover,
loadingBuilder:
(context, child, loadingProgress) {
if (loadingProgress == null) return child;
return Container(
color: const Color(0xFF1F212E),
child: const Center(
child: CircularProgressIndicator(
color: Color(0xff7DDFA4),
),
),
);
},
errorBuilder: (context, error, stackTrace) {
print('背景图加载失败: $error');
return Container(
color: const Color(0xFF1F212E),
);
},
),
// 渐变遮罩
Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.black.withOpacity(0.2),
Colors.black.withOpacity(0.5),
],
),
),
),
],
),
),
),
// 底部背景
Positioned(
left: 0,
right: 0,
top: 230,
bottom: 0,
child: Container(
width: MediaQuery.of(context).size.width,
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage('images/mine_bg.png'),
fit: BoxFit.fill,
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(left: 16, top: 16),
child: Text(
"TA 的发布($total)",
style: const TextStyle(
color: Color(0xffffffff),
fontSize: 16,
fontWeight: FontWeight.bold,
decoration: TextDecoration.none,
),
),
),
Expanded(
child: isLoading
? const Center(
child: CircularProgressIndicator(
color: Color(0xff7DDFA4),
),
)
: publishList.isEmpty
? const Center(
child: Text(
'暂无数据',
style: TextStyle(
color: Colors.white,
fontSize: 14,
),
),
)
: RefreshIndicator(
onRefresh: () => _fetchPublishData(),
child: SingleChildScrollView(
physics:
const AlwaysScrollableScrollPhysics(),
controller: _scrollController,
child: Column(
children: [
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 12),
child: WorkGridView(
controller:
null, // 移除 WorkGridView 的滚动控制器
items: publishList,
onTap: (index) async {
if (index <
publishList.length) {
final workItem =
publishList[index];
final result =
await Navigator.pushNamed(
context,
'/infoDetail',
arguments: {
'workId': workItem.workId,
'isLiked':
workItem.isAddLike,
'likeCount': int.parse(
workItem.count),
},
);
if (result != null &&
result is Map<String,
dynamic>) {
setState(() {
if (index <
publishList.length) {
final updatedItem =
WorkItem(
workId:
workItem.workId,
imageUrl:
workItem.imageUrl,
title: workItem.title,
count: result[
'likeCount']
.toString(),
isAddLike:
result['isLiked'],
);
publishList[index] =
updatedItem;
}
});
}
}
},
showUpvote: false,
),
),
if (_isLoadingMore)
const Padding(
padding: EdgeInsets.all(8.0),
child: Center(
child:
CircularProgressIndicator(
color: Color(0xff7DDFA4),
),
),
),
],
),
),
),
),
],
),
),
),
// 顶部内容(头像、昵称等)
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 顶部导航栏
Container(
padding: const EdgeInsets.only(top: 30),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
IconButton(
icon: Image.asset(
'images/arraw.png',
width: 11,
height: 22,
fit: BoxFit.cover,
),
onPressed: () {
Navigator.pop(context, {
'isFollowed': _isFollowed,
'userId': widget.work['userId'],
});
},
),
],
),
),
// 用户信息
Container(
padding: const EdgeInsets.only(left: 16, right: 16),
child: Row(
children: [
CircleAvatar(
radius: 35,
backgroundImage: userDetail['avatar'] != null
? NetworkImage(userDetail['avatar'])
: const AssetImage('images/default_avatar.png')
as ImageProvider,
onBackgroundImageError: (exception, stackTrace) {
print('头像加载失败: $exception');
},
),
const SizedBox(width: 16.0),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
userDetail['nickName'] ?? '未知用户',
style: const TextStyle(
fontSize: 20,
color: Colors.white,
decoration: TextDecoration.none,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 10),
SizedBox(
width: MediaQuery.of(context).size.width - 135,
child: Text(
'个性签名:${userDetail['signature'] ?? '暂无签名'}',
style: const TextStyle(
color: Color(0xffC1C1C1),
fontSize: 12,
decoration: TextDecoration.none,
),
softWrap: true,
overflow: TextOverflow.ellipsis,
maxLines: 2,
),
),
],
),
],
),
),
// 关注按钮
if (!_isOwnWork) ...[
const SizedBox(height: 20),
Container(
width: 65,
margin: const EdgeInsets.only(left: 100), // 与昵称左对齐
child: SizedBox(
width: 65, // 设置按钮宽度为65
height: 28, // 设置按钮高度为28
child: TextButton(
onPressed: _toggleFollow,
style: ButtonStyle(
shape: MaterialStateProperty.all<
RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
),
side: MaterialStateProperty.all(
BorderSide(
color: _isFollowed
? Colors.grey
: const Color(0xffF42845),
width: 0.67),
),
padding: MaterialStateProperty.all(
EdgeInsets.zero, // 去掉内边距,确保文字居中
),
backgroundColor: MaterialStateProperty.all(
_isFollowed
? Colors.transparent
: const Color(0xffF42845),
),
minimumSize: MaterialStateProperty.all(
const Size(65, 28)), // 最小尺寸
maximumSize: MaterialStateProperty.all(
const Size(65, 28)), // 最大尺寸
fixedSize: MaterialStateProperty.all(
const Size(65, 28)), // 固定尺寸
),
child: Text(
_isFollowed ? '已关注' : '+关注',
style: TextStyle(
color: _isFollowed ? Colors.grey : Colors.white,
fontSize: 14,
),
),
),
),
),
],
],
),
],
),
),
),
);
}
}