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

258 lines
8.6 KiB
Dart

import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:http_parser/http_parser.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import '../../apis/app.dart';
class ChangeBackgroundPage extends StatefulWidget {
final String imagePath; // 接收图片路径
const ChangeBackgroundPage({super.key, required this.imagePath});
@override
State<ChangeBackgroundPage> createState() => _ChangeBackgroundPageState();
}
class _ChangeBackgroundPageState extends State<ChangeBackgroundPage> {
String? _imagePath;
String? _phoneNumber;
@override
void initState() {
super.initState();
_imagePath = widget.imagePath; // 初始化时将传递的路径赋值给 _imagePath
print('Image path: $_imagePath'); // 打印路径检查
// 获取本地手机号
_loadPhoneNumber();
}
Future<void> _loadPhoneNumber() async {
final prefs = await SharedPreferences.getInstance();
setState(() {
_phoneNumber = prefs.getString('phone');
print('获取到的手机号: $_phoneNumber');
});
}
Future<void> _pickAndCropImage() async {
try {
final List<AssetEntity>? result = await AssetPicker.pickAssets(
context,
pickerConfig: const AssetPickerConfig(
textDelegate: AssetPickerTextDelegate(),
maxAssets: 1,
requestType: RequestType.image, // 只允许选择图片
themeColor: Color(0xff7CDBC8),
),
);
if (result != null && result.isNotEmpty) {
final file = await result.first.file;
if (file != null && mounted) {
CroppedFile? croppedFile = await ImageCropper().cropImage(
sourcePath: file.path,
aspectRatio: const CropAspectRatio(ratioX: 4, ratioY: 3),
uiSettings: [
AndroidUiSettings(
toolbarTitle: '裁剪图片',
toolbarColor: const Color(0xff0C0C16),
toolbarWidgetColor: Colors.white,
initAspectRatio: CropAspectRatioPreset.original,
lockAspectRatio: true,
hideBottomControls: true,
),
IOSUiSettings(
minimumAspectRatio: 1.0,
),
],
);
if (croppedFile != null && mounted) {
try {
// 显示加载指示器
showDialog(
context: context,
barrierDismissible: false,
builder: (context) => const Center(
child: CircularProgressIndicator(),
),
);
// 获取文件信息
final file = File(croppedFile.path);
final fileSize = await file.length();
print('裁剪后的图片大小: ${fileSize} bytes');
print('裁剪后的图片路径: ${croppedFile.path}');
// 准备上传数据
final formData = FormData.fromMap({
'background': await MultipartFile.fromFile(
croppedFile.path,
filename: 'background.jpg', // 修改文件名
contentType: MediaType('image', 'jpeg'), // 修改content type
),
'username': _phoneNumber,
});
print('准备上传的表单数据: ${formData.fields}');
// 调用接口上传裁剪后的图片
final result = await userApi.getUpdateUserBg(formData);
print('API响应结果: $result');
// 关闭加载指示器
if (mounted) Navigator.pop(context);
if (result['code'] == 200) {
if (mounted) {
Navigator.pushNamedAndRemoveUntil(
context,
'/tabs',
(route) => false,
arguments: {'initialIndex': 4},
);
}
} else {
// 显示详细的错误信息
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('更新失败: ${result['message'] ?? '未知错误'}'),
backgroundColor: Colors.red,
),
);
}
}
} catch (e, stackTrace) {
print('上传过程中发生错误: $e');
print('错误堆栈: $stackTrace');
// 关闭加载指示器
if (mounted) Navigator.pop(context);
// 显示详细的错误信息
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('上传失败: $e'),
backgroundColor: Colors.red,
),
);
}
}
}
}
}
} catch (e, stackTrace) {
print('选择或裁剪过程中发生错误: $e');
print('错误堆栈: $stackTrace');
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('处理图片失败: $e'),
backgroundColor: Colors.red,
),
);
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Image.asset('images/close.png', width: 16, height: 16),
onPressed: () => Navigator.of(context).pop(),
),
),
body: Container(
decoration: const BoxDecoration(color: Color(0xff0C0C16)),
child: Stack(
children: [
Positioned(
top: 20,
left: 0,
right: 0,
bottom: 100,
child: Center(
child: _imagePath != null
? _imagePath!.startsWith('http')
? Image.network(
_imagePath!,
fit: BoxFit.contain, // 修改为 contain 以确保图片完整显示
)
: File(_imagePath!).existsSync()
? Image.file(
File(_imagePath!),
fit: BoxFit.contain,
)
: Image.asset('images/detail_bg.png')
: const Center(child: Text('No image selected')),
),
),
Positioned(
left: 16,
right: 16,
bottom: 50,
child: Container(
height: 44,
decoration: BoxDecoration(
color:
const Color(0xFF96FBE9).withOpacity(0.2), // 设置填充颜色透明度为20%
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: const Color(0xFF96FBE9), // 设置边框颜色
width: 0.5,
),
),
child: Row(
children: [
Expanded(
child: Padding(
padding: const EdgeInsets.only(left: 16),
child: GestureDetector(
onTap: _pickAndCropImage,
child: Text(
"更换背景",
style: TextStyle(
color: Colors.white,
fontSize: 14,
),
),
),
),
),
Padding(
padding: const EdgeInsets.only(right: 12),
child: Container(
width: 24,
height: 24,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(4),
),
child: Image.asset(
'images/send.png',
width: 20,
height: 20,
color: Colors.white,
),
),
),
],
),
),
),
],
),
),
);
}
}