修改设备别名接口+UI

This commit is contained in:
mmc
2026-02-27 21:04:07 +08:00
parent 5170eeb4e7
commit 952bab03f5
10 changed files with 633 additions and 209 deletions

View File

@@ -7,6 +7,7 @@ import 'package:maibu_satabot_v2/features/devices/data/datasources/impl/device_h
import 'package:maibu_satabot_v2/features/devices/domain/repositories/device_repository.dart'; import 'package:maibu_satabot_v2/features/devices/domain/repositories/device_repository.dart';
import 'package:maibu_satabot_v2/features/devices/domain/usecases/get_user_device_usecase.dart'; import 'package:maibu_satabot_v2/features/devices/domain/usecases/get_user_device_usecase.dart';
import 'package:maibu_satabot_v2/features/devices/domain/usecases/unbind_device_usecase.dart'; import 'package:maibu_satabot_v2/features/devices/domain/usecases/unbind_device_usecase.dart';
import 'package:maibu_satabot_v2/features/devices/domain/usecases/update_devicename_usecase.dart';
import 'package:maibu_satabot_v2/features/devices/presentation/bloc/devices_cubit.dart'; import 'package:maibu_satabot_v2/features/devices/presentation/bloc/devices_cubit.dart';
import 'package:maibu_satabot_v2/features/remote_control/data/repositories/remote_control_repository_impl.dart'; import 'package:maibu_satabot_v2/features/remote_control/data/repositories/remote_control_repository_impl.dart';
import 'package:maibu_satabot_v2/features/remote_control/domain/repositories/remote_control_repository.dart'; import 'package:maibu_satabot_v2/features/remote_control/domain/repositories/remote_control_repository.dart';
@@ -103,12 +104,13 @@ Future<void> init() async {
sl.registerLazySingleton(() => DiffSteerUseCase()); sl.registerLazySingleton(() => DiffSteerUseCase());
sl.registerLazySingleton(() => DeviceWorkHostrirty(sl())); sl.registerLazySingleton(() => DeviceWorkHostrirty(sl()));
sl.registerLazySingleton(() => UnbindDeviceUseCase(sl())); sl.registerLazySingleton(() => UnbindDeviceUseCase(sl()));
sl.registerLazySingleton(() => UpdateDevicenameUsecase(sl()));
/// 5. 状态管理 (Cubit/Bloc) /// 5. 状态管理 (Cubit/Bloc)
sl.registerLazySingleton(() => AppUserCubit()); // AuthCubit 依赖它,必须先注册 sl.registerLazySingleton(() => AppUserCubit()); // AuthCubit 依赖它,必须先注册
sl.registerLazySingleton(() => GetDeviceLocationUseCase(sl())); sl.registerLazySingleton(() => GetDeviceLocationUseCase(sl()));
sl.registerLazySingleton( sl.registerLazySingleton(
() => DevicesCubit(sl(), sl(), sl(), sl(), sl(), sl()), () => DevicesCubit(sl(), sl(), sl(), sl(), sl(), sl(), sl()),
); );
sl.registerFactory(() => RemoteControlCubit(sl())); sl.registerFactory(() => RemoteControlCubit(sl()));

View File

@@ -4,6 +4,7 @@ abstract class DeviceHttpDatasource {
Future<List<DeviceEntity>> getUserDevices(String username); Future<List<DeviceEntity>> getUserDevices(String username);
Future<int> bindDevice(String deviceId, String deviceAlias); Future<int> bindDevice(String deviceId, String deviceAlias);
Future<int> unbindDevice(String deviceId, String deviceName); Future<int> unbindDevice(String deviceId, String deviceName);
Future<int> updateDeviceName(String deviceId, String deviceName);
Future<int> switchDevice(String platform, String deviceId); Future<int> switchDevice(String platform, String deviceId);
Future<dynamic> getDeviceLocation(String username) async {} Future<dynamic> getDeviceLocation(String username) async {}

View File

@@ -92,7 +92,27 @@ class DeviceHttpDatasourceImpl implements DeviceHttpDatasource {
throw Exception(data['msg']); throw Exception(data['msg']);
} }
return data['data']; return data['data'] == true ? 1 : 0; // 根据接口返回的布尔值转换为 int
}
Future<int> updateDeviceName(String deviceId, String deviceName) async {
final response = await dio.post(
'/forward/device/updateDeviceAlias',
data: {"deviceId": deviceId, "deviceAlias": deviceName},
);
print('修改别名响应: ${response}'); // 调试输出响应数据
final data = response.data;
if (response.statusCode != 200) {
throw Exception('网络错误');
}
if (data['code'] != 200) {
throw Exception(data['msg']);
}
return data['data'] == true ? 1 : 0; // 根据接口返回的布尔值转换为 int
} }
@override @override

View File

@@ -61,6 +61,19 @@ class DeviceRepositoryImpl implements DeviceRepository {
return Left(DeviceFailure(cleanMessage)); return Left(DeviceFailure(cleanMessage));
} }
} }
@override
Future<Either<DeviceFailure, int>> updateDeviceName(String deviceId, String deviceName) async {
try {
var result = await _deviceHttpDatasource.updateDeviceName(deviceId, deviceName);
return Right(result);
} on DioException catch (e) {
final String serverMessage = e.response?.data['msg'] ?? "网络连接异常";
return Left(DeviceFailure(serverMessage));
} catch (e) {
final cleanMessage = e.toString().replaceFirst('Exception: ', '');
return Left(DeviceFailure(cleanMessage));
}
}
@override @override
Future<Either<DeviceFailure, int>> switchDevice( Future<Either<DeviceFailure, int>> switchDevice(

View File

@@ -15,6 +15,10 @@ abstract class DeviceRepository {
String deviceId, String deviceId,
String deviceName, String deviceName,
); );
Future<Either<DeviceFailure, int>> updateDeviceName(
String deviceId,
String deviceAlias,
);
Future<Either<DeviceFailure, int>> switchDevice( Future<Either<DeviceFailure, int>> switchDevice(
String platform, String platform,
String deviceId, String deviceId,

View File

@@ -0,0 +1,26 @@
import 'package:fpdart/fpdart.dart';
import 'package:maibu_satabot_v2/core/domain/usecases/base_usecase.dart';
import 'package:maibu_satabot_v2/core/error/failure.dart';
import 'package:maibu_satabot_v2/features/devices/domain/repositories/device_repository.dart';
class UpdateDevicenameUsecase
implements BaseUseCase<int, UpdateDevicenameParams> {
final DeviceRepository repository;
UpdateDevicenameUsecase(this.repository);
@override
Future<Either<Failure, int>> call(UpdateDevicenameParams params) async {
return await repository.updateDeviceName(
params.deviceId,
params.deviceAlias,
);
}
}
class UpdateDevicenameParams {
final String deviceId;
final String deviceAlias;
UpdateDevicenameParams(this.deviceId, this.deviceAlias);
}

View File

@@ -3,6 +3,7 @@ import 'package:maibu_satabot_v2/features/devices/domain/entities/device_entity.
import 'package:maibu_satabot_v2/features/devices/domain/repositories/device_repository.dart'; import 'package:maibu_satabot_v2/features/devices/domain/repositories/device_repository.dart';
import 'package:maibu_satabot_v2/features/devices/domain/usecases/get_user_device_usecase.dart'; import 'package:maibu_satabot_v2/features/devices/domain/usecases/get_user_device_usecase.dart';
import 'package:maibu_satabot_v2/features/devices/domain/usecases/unbind_device_usecase.dart'; import 'package:maibu_satabot_v2/features/devices/domain/usecases/unbind_device_usecase.dart';
import 'package:maibu_satabot_v2/features/devices/domain/usecases/update_devicename_usecase.dart';
import '../../domain/usecases/delete_work_record_usecase.dart'; import '../../domain/usecases/delete_work_record_usecase.dart';
import '../../domain/usecases/get_device_location_usecase.dart'; import '../../domain/usecases/get_device_location_usecase.dart';
@@ -16,6 +17,7 @@ class DevicesCubit extends Cubit<DevicesState> {
final GetWorkRecordUseCase _getWorkRecordUseCase; final GetWorkRecordUseCase _getWorkRecordUseCase;
final DeleteWorkRecordUseCase _deleteWorkRecordUseCase; final DeleteWorkRecordUseCase _deleteWorkRecordUseCase;
final UnbindDeviceUseCase _unbindDeviceUseCase; final UnbindDeviceUseCase _unbindDeviceUseCase;
final UpdateDevicenameUsecase _updateDevicename;
DevicesCubit( DevicesCubit(
this.repository, this.repository,
@@ -24,10 +26,17 @@ class DevicesCubit extends Cubit<DevicesState> {
this._getWorkRecordUseCase, this._getWorkRecordUseCase,
this._deleteWorkRecordUseCase, this._deleteWorkRecordUseCase,
this._unbindDeviceUseCase, this._unbindDeviceUseCase,
this._updateDevicename,
) : super(const DevicesState()); ) : super(const DevicesState());
Future<void> unbindDevice(String deviceId, String deviceName) async { Future<void> unbindDevice(String deviceId, String deviceName) async {
emit(state.copyWith(isLoading: true, errorMessage: '')); emit(
state.copyWith(
isLoading: true,
errorMessage: '',
operationType: DeviceOperationType.unbind,
),
);
try { try {
final params = UnbindDeviceParams(deviceId, deviceName); final params = UnbindDeviceParams(deviceId, deviceName);
@@ -38,6 +47,7 @@ class DevicesCubit extends Cubit<DevicesState> {
state.copyWith( state.copyWith(
isLoading: false, isLoading: false,
errorMessage: failure.message ?? '解绑设备失败', errorMessage: failure.message ?? '解绑设备失败',
operationType: DeviceOperationType.none, // 操作结束重置
), ),
), ),
(successCode) { (successCode) {
@@ -56,6 +66,7 @@ class DevicesCubit extends Cubit<DevicesState> {
? null ? null
: state.selectedDevice, : state.selectedDevice,
errorMessage: '', errorMessage: '',
operationType: DeviceOperationType.none,
), ),
); );
} else { } else {
@@ -63,6 +74,7 @@ class DevicesCubit extends Cubit<DevicesState> {
state.copyWith( state.copyWith(
isLoading: false, isLoading: false,
errorMessage: '解绑失败:状态码 $successCode', errorMessage: '解绑失败:状态码 $successCode',
operationType: DeviceOperationType.none,
), ),
); );
} }
@@ -70,7 +82,68 @@ class DevicesCubit extends Cubit<DevicesState> {
); );
} catch (e) { } catch (e) {
emit( emit(
state.copyWith(isLoading: false, errorMessage: '解绑异常:${e.toString()}'), state.copyWith(isLoading: false, errorMessage: '解绑异常:${e.toString()}', operationType: DeviceOperationType.none),
);
}
}
Future<void> updateDeviceName(String deviceId, String deviceName) async {
emit(
state.copyWith(
isLoading: true,
errorMessage: '',
operationType: DeviceOperationType.updateName,
),
);
try {
final params = UpdateDevicenameParams(deviceId, deviceName);
final result = await _updateDevicename.call(params);
result.fold(
(failure) => emit(
state.copyWith(
isLoading: false,
errorMessage: failure.message ?? '更新设备名称失败',
operationType: DeviceOperationType.none,
),
),
(successCode) {
// 核心修复:int 转 bool 条件判断
print('更新设备名称结果代码: $successCode'); // 调试输出结果代码
final isSuccess = successCode == 1; // 显式转为 bool
if (isSuccess) {
//final updatedDevices = state.devices?.map((device) {
// return device.deviceName == deviceId ? device.copyWith(deviceName: deviceName) : device;
//}).toList();
emit(
state.copyWith(
isLoading: false,
//devices: updatedDevices,
//selectedDevice: state.selectedDevice?.deviceName == deviceId ? state.selectedDevice?.copyWith(deviceName: deviceName) : state.selectedDevice,
errorMessage: '',
operationType: DeviceOperationType.none,
),
);
} else {
emit(
state.copyWith(
isLoading: false,
errorMessage: '更新设备名称失败:状态码 $successCode',
operationType: DeviceOperationType.none,
),
);
}
},
);
} catch (e) {
emit(
state.copyWith(
isLoading: false,
errorMessage: '更新设备名称异常:${e.toString()}',
operationType: DeviceOperationType.none,
),
); );
} }
} }

View File

@@ -1,5 +1,11 @@
import 'package:equatable/equatable.dart'; import 'package:equatable/equatable.dart';
import 'package:maibu_satabot_v2/features/devices/domain/entities/device_entity.dart'; import 'package:maibu_satabot_v2/features/devices/domain/entities/device_entity.dart';
enum DeviceOperationType {
none, // 无操作
unbind, // 解绑设备
updateName, // 修改设备名称
}
class DevicesState extends Equatable { class DevicesState extends Equatable {
final List<DeviceEntity> devices; // 名下所有设备列表 final List<DeviceEntity> devices; // 名下所有设备列表
@@ -9,6 +15,7 @@ class DevicesState extends Equatable {
final double? deviceLatitude; // 新增字段 final double? deviceLatitude; // 新增字段
final double? deviceLongitude; // 新增字段 final double? deviceLongitude; // 新增字段
final List<Map<String, dynamic>>? workRecords; final List<Map<String, dynamic>>? workRecords;
final DeviceOperationType operationType; // 标记当前操作类型
const DevicesState({ const DevicesState({
this.devices = const [], this.devices = const [],
this.selectedDevice, this.selectedDevice,
@@ -16,7 +23,8 @@ class DevicesState extends Equatable {
this.errorMessage, this.errorMessage,
this.deviceLatitude, this.deviceLatitude,
this.deviceLongitude, this.deviceLongitude,
this.workRecords this.workRecords,
this.operationType = DeviceOperationType.none, // 默认无操作
}); });
// 使用 copyWith 方便局部更新状态 // 使用 copyWith 方便局部更新状态
@@ -28,6 +36,7 @@ class DevicesState extends Equatable {
double? deviceLatitude, double? deviceLatitude,
double? deviceLongitude, double? deviceLongitude,
List<Map<String, dynamic>>? workRecords, List<Map<String, dynamic>>? workRecords,
DeviceOperationType? operationType,
}) { }) {
return DevicesState( return DevicesState(
devices: devices ?? this.devices, devices: devices ?? this.devices,
@@ -37,6 +46,7 @@ class DevicesState extends Equatable {
deviceLatitude: deviceLatitude ?? this.deviceLatitude, deviceLatitude: deviceLatitude ?? this.deviceLatitude,
deviceLongitude: deviceLongitude ?? this.deviceLongitude, deviceLongitude: deviceLongitude ?? this.deviceLongitude,
workRecords: workRecords ?? this.workRecords, workRecords: workRecords ?? this.workRecords,
operationType: operationType ?? this.operationType, // 更新操作类型
); );
} }

View File

@@ -374,6 +374,7 @@ class ImmersionHeader extends StatelessWidget {
), ),
], ],
), ),
const SizedBox(height: 6),
const Text( const Text(
"点击查看详情", "点击查看详情",
style: TextStyle(color: Colors.grey, fontSize: 12), style: TextStyle(color: Colors.grey, fontSize: 12),

View File

@@ -22,36 +22,54 @@ class _MachineDetailsPageState extends State<MachineDetailsPage> {
late String _deviceName; late String _deviceName;
late String _deviceId; late String _deviceId;
BuildContext? _dialogContext; BuildContext? _dialogContext;
BuildContext? _editNameSheetContext;
BuildContext? _loadingDialogContext; // 解绑加载弹窗
BuildContext? _updateLoadingContext; // 修改名称加载弹窗
bool _isUpdatingName = false;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_deviceName = (widget.device?.deviceAlias?.trim().isEmpty ?? true) _deviceName = (widget.device?.deviceAlias?.trim().isEmpty ?? true)
? '未知设备' ? '未知设备'
: widget.device!.deviceAlias!; : widget.device!.deviceAlias!;
_deviceId = widget.device?.deviceName ?? ''; _deviceId = widget.device?.deviceName ?? '';
_nameController = TextEditingController(text: _deviceName);
_nameController = TextEditingController();
} }
@override @override
void dispose() { void dispose() {
_nameController.dispose(); _nameController.dispose();
// 兜底关闭所有弹窗
if (_loadingDialogContext != null &&
Navigator.canPop(_loadingDialogContext!)) {
Navigator.pop(_loadingDialogContext!);
}
if (_updateLoadingContext != null &&
Navigator.canPop(_updateLoadingContext!)) {
Navigator.pop(_updateLoadingContext!);
}
if (_dialogContext != null && Navigator.canPop(_dialogContext!)) {
Navigator.pop(_dialogContext!);
}
if (_editNameSheetContext != null &&
Navigator.canPop(_editNameSheetContext!)) {
Navigator.pop(_editNameSheetContext!);
}
super.dispose(); super.dispose();
} }
/// 弹出修改设备名称底部抽屉 /// 弹出修改设备名称底部抽屉(保持不变)
void _showEditNameSheet() { void _showEditNameSheet() {
_nameController.text = _deviceName; _nameController.text = _deviceName;
Future<void> bottomSheetFuture = showModalBottomSheet(
showModalBottomSheet(
context: context, context: context,
isScrollControlled: true, isScrollControlled: true,
shape: const RoundedRectangleBorder( shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(16)), borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
), ),
builder: (ctx) { builder: (ctx) {
_editNameSheetContext = ctx;
return Padding( return Padding(
padding: EdgeInsets.only( padding: EdgeInsets.only(
left: 20, left: 20,
@@ -74,6 +92,7 @@ class _MachineDetailsPageState extends State<MachineDetailsPage> {
decoration: const InputDecoration( decoration: const InputDecoration(
hintText: "请输入设备名称", hintText: "请输入设备名称",
border: OutlineInputBorder(), border: OutlineInputBorder(),
counterText: "",
), ),
), ),
const SizedBox(height: 10), const SizedBox(height: 10),
@@ -81,34 +100,45 @@ class _MachineDetailsPageState extends State<MachineDetailsPage> {
children: [ children: [
Expanded( Expanded(
child: OutlinedButton( child: OutlinedButton(
onPressed: () => Navigator.pop(ctx), onPressed: () {
_isUpdatingName = false;
Navigator.pop(ctx);
},
child: const Text("取消"), child: const Text("取消"),
), ),
), ),
const SizedBox(width: 12), const SizedBox(width: 12),
Expanded( Expanded(
child: OutlinedButton( child: OutlinedButton(
onPressed: () { onPressed: _isUpdatingName
final text = _nameController.text.trim(); ? null
: () async {
if (text.isEmpty) { final text = _nameController.text.trim();
ScaffoldMessenger.of(context).showSnackBar( if (text.isEmpty) {
const SnackBar(content: Text("名称不能为空")), if (context.mounted) {
); ScaffoldMessenger.of(context).showSnackBar(
return; const SnackBar(content: Text("名称不能为空")),
} );
}
setState(() { return;
_deviceName = text; }
}); if (text == _deviceName) {
Navigator.pop(ctx);
Navigator.pop(ctx); return;
}
ScaffoldMessenger.of( setState(() => _isUpdatingName = true);
context, await _executeUpdateDeviceName(text);
).showSnackBar(SnackBar(content: Text("已修改为:$text"))); },
}, child: _isUpdatingName
child: const Text("确认"), ? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
color: Colors.white,
),
)
: const Text("确认修改"),
), ),
), ),
], ],
@@ -118,21 +148,49 @@ class _MachineDetailsPageState extends State<MachineDetailsPage> {
); );
}, },
); );
bottomSheetFuture.whenComplete(() {
setState(() {
_isUpdatingName = false;
_editNameSheetContext = null;
});
});
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
if (widget.device == null) { if (widget.device == null) {
return const Scaffold(body: Center(child: Text("未获取到设备信息"))); return Scaffold(
backgroundColor: const Color(0xFFF5F5F5),
appBar: AppBar(
title: const Text('设备详情'),
leading: IconButton(
icon: const Icon(Icons.arrow_back_ios),
onPressed: () {
// 优化1:先刷新列表,再返回(保证刷新逻辑执行)
// 核心:返回上一页
Navigator.pop(context);
if (context.mounted) {
final username =
context.read<AppUserCubit>().state.user?.username ?? "";
context.read<DevicesCubit>().fetchAllDevices(username);
}
},
),
),
body: const Center(child: Text("未获取到设备信息")),
);
} }
final currentDevice = widget.device!; final currentDevice = widget.device!;
return BlocListener<DevicesCubit, DevicesState>( return BlocListener<DevicesCubit, DevicesState>(
listener: (context, state) { listener: (context, state) {
// 只有解绑操作触发的状态变化才处理 if (state.operationType == DeviceOperationType.unbind) {
if (state.isLoading || state.errorMessage != null) {
_handleUnbindResult(state); _handleUnbindResult(state);
} }
if (state.operationType == DeviceOperationType.updateName) {
_handleUpdateNameResult(state);
}
}, },
child: Scaffold( child: Scaffold(
backgroundColor: const Color(0xFFF5F5F5), backgroundColor: const Color(0xFFF5F5F5),
@@ -144,8 +202,18 @@ class _MachineDetailsPageState extends State<MachineDetailsPage> {
), ),
leading: IconButton( leading: IconButton(
icon: const Icon(Icons.arrow_back_ios), icon: const Icon(Icons.arrow_back_ios),
onPressed: () => Navigator.pop(context), onPressed: () {
Navigator.pop(context);
if (context.mounted) {
final username =
context.read<AppUserCubit>().state.user?.username ?? "";
context.read<DevicesCubit>().fetchAllDevices(username);
}
},
), ),
elevation: 1,
backgroundColor: Colors.white,
foregroundColor: Colors.black,
), ),
body: SingleChildScrollView( body: SingleChildScrollView(
padding: const EdgeInsets.all(16), padding: const EdgeInsets.all(16),
@@ -153,7 +221,7 @@ class _MachineDetailsPageState extends State<MachineDetailsPage> {
children: [ children: [
_buildDeviceStatusCard(currentDevice), _buildDeviceStatusCard(currentDevice),
const SizedBox(height: 16), const SizedBox(height: 16),
_buildBasicInfoCard(context, currentDevice), // 传递context和设备数据 _buildBasicInfoCard(context, currentDevice),
const SizedBox(height: 16), const SizedBox(height: 16),
_buildResourceCenterCard(), _buildResourceCenterCard(),
const SizedBox(height: 24), const SizedBox(height: 24),
@@ -165,25 +233,52 @@ class _MachineDetailsPageState extends State<MachineDetailsPage> {
); );
} }
/// 设备状态卡片 /// 设备状态卡片(保持不变)
Widget _buildDeviceStatusCard(DeviceEntity device) { Widget _buildDeviceStatusCard(DeviceEntity device) {
return Container( return Container(
padding: const EdgeInsets.all(24), padding: const EdgeInsets.all(24),
decoration: BoxDecoration( decoration: BoxDecoration(
color: Colors.white, color: Colors.white,
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.1),
blurRadius: 8,
offset: const Offset(0, 2),
),
],
), ),
child: Column( child: Column(
children: [ children: [
Image.asset('assets/images/car.png', width: 300, fit: BoxFit.contain), Image.asset(
'assets/images/car.png',
width: 300,
fit: BoxFit.contain,
errorBuilder: (context, error, stackTrace) {
return const Icon(
Icons.device_hub,
size: 100,
color: Colors.grey,
);
},
),
const SizedBox(height: 12), const SizedBox(height: 12),
Text( Container(
device.isOnline ? '在线' : '离线', padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
style: TextStyle( decoration: BoxDecoration(
fontSize: 14,
color: device.isOnline color: device.isOnline
? const Color(0xFF00C853) ? const Color(0xFF00C853).withOpacity(0.1)
: const Color(0xFF999999), : const Color(0xFF999999).withOpacity(0.1),
borderRadius: BorderRadius.circular(12),
),
child: Text(
device.isOnline ? '在线' : '离线',
style: TextStyle(
fontSize: 14,
color: device.isOnline
? const Color(0xFF00C853)
: const Color(0xFF999999),
),
), ),
), ),
], ],
@@ -191,20 +286,21 @@ class _MachineDetailsPageState extends State<MachineDetailsPage> {
); );
} }
// 基本信息卡片(接收context和设备数据参数) /// 基本信息卡片(保持不变)
Widget _buildBasicInfoCard(BuildContext context, DeviceEntity device) { Widget _buildBasicInfoCard(BuildContext context, DeviceEntity device) {
// 处理设备名称(空值兜底)
final deviceName = (device.deviceAlias?.trim() ?? '').isEmpty
? '未知设备'
: device.deviceAlias!;
// 处理设备ID(空值兜底)
final deviceId = device.deviceName ?? '未知ID'; final deviceId = device.deviceName ?? '未知ID';
return Container( return Container(
padding: const EdgeInsets.all(16), padding: const EdgeInsets.all(16),
decoration: BoxDecoration( decoration: BoxDecoration(
color: Colors.white, color: Colors.white,
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.1),
blurRadius: 8,
offset: const Offset(0, 2),
),
],
), ),
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
@@ -216,17 +312,16 @@ class _MachineDetailsPageState extends State<MachineDetailsPage> {
style: TextStyle(fontSize: 14, color: Color(0xFF999999)), style: TextStyle(fontSize: 14, color: Color(0xFF999999)),
), ),
), ),
// 设备名称行 - 传递context参数
_buildInfoRow( _buildInfoRow(
context: context, // 关键:补上必填的context参数 context: context,
icon: Icons.info_outline, icon: Icons.info_outline,
label: '设备名称', label: '设备名称',
trailing: GestureDetector( trailing: GestureDetector(
onTap: _showEditNameSheet, onTap: _isUpdatingName ? null : _showEditNameSheet,
child: Row( child: Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
Text(_deviceName), Text(_deviceName, style: const TextStyle(fontSize: 16)),
const SizedBox(width: 8), const SizedBox(width: 8),
const Icon(Icons.edit, size: 16, color: Color(0xFF007AFF)), const Icon(Icons.edit, size: 16, color: Color(0xFF007AFF)),
], ],
@@ -234,40 +329,23 @@ class _MachineDetailsPageState extends State<MachineDetailsPage> {
), ),
), ),
const Divider(height: 32, color: Color(0xFFF0F0F0)), const Divider(height: 32, color: Color(0xFFF0F0F0)),
// 设备ID行 - 传递context参数
// 设备ID行 - 传递context参数
_buildInfoRow( _buildInfoRow(
context: context, context: context,
icon: Icons.shield_outlined, icon: Icons.shield_outlined,
label: '设备ID', label: '设备ID',
trailing: Column( trailing: Column(
crossAxisAlignment: CrossAxisAlignment.end, // 右对齐 crossAxisAlignment: CrossAxisAlignment.end,
mainAxisSize: MainAxisSize.min, // 只占必要高度 mainAxisSize: MainAxisSize.min,
children: [ children: [
// 核心修改:去掉宽度限制,允许换行显示全部ID
SizedBox( SizedBox(
// 取消固定宽度,让文本自适应(也可设置最大宽度适配屏幕) width: MediaQuery.of(context).size.width - 180,
width:
MediaQuery.of(context).size.width - 180, // 适配屏幕宽度(避免超出)
child: GestureDetector( child: GestureDetector(
onLongPress: () { onLongPress: () => _copyToClipboard(deviceId, '设备ID已复制'),
// 长按文本复制
Clipboard.setData(ClipboardData(text: deviceId));
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('设备ID已复制'),
duration: Duration(seconds: 1),
),
);
}
},
child: Text( child: Text(
deviceId, deviceId,
textAlign: TextAlign.right, // 右对齐更美观 textAlign: TextAlign.right,
softWrap: true, // 允许换行 softWrap: true,
overflow: TextOverflow.visible, // 显示全部内容(无省略号) overflow: TextOverflow.visible,
style: const TextStyle( style: const TextStyle(
fontSize: 14, fontSize: 14,
color: Colors.black87, color: Colors.black87,
@@ -275,45 +353,15 @@ class _MachineDetailsPageState extends State<MachineDetailsPage> {
), ),
), ),
), ),
const SizedBox(height: 4), // 文本和复制图标间距 const SizedBox(height: 4),
// 复制图标单独一行
GestureDetector( GestureDetector(
onTap: () { onTap: () => _copyToClipboard(deviceId, '设备ID已复制到剪贴板'),
Clipboard.setData(ClipboardData(text: deviceId));
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('设备ID已复制到剪贴板'),
duration: Duration(seconds: 1),
),
);
}
},
child: const Icon( child: const Icon(
Icons.copy, Icons.copy,
size: 16, size: 16,
color: Color(0xFF999999), color: Color(0xFF999999),
), ),
), ),
//_buildInfoRow(
// context: context, // 关键:补上必填的context参数
// icon: Icons.info_outline,
// label: '激活时间',
// trailing: Row(
// mainAxisSize: MainAxisSize.min, // 防止Row撑满宽度
// children: [
// // 显示真实设备名称
// Text(activeTime),
// const SizedBox(width: 8),
// const Icon(
// Icons.edit,
// size: 16,
// color: Color(0xFF007AFF),
// ),
// ],
// ),
//),
], ],
), ),
), ),
@@ -322,13 +370,20 @@ class _MachineDetailsPageState extends State<MachineDetailsPage> {
); );
} }
// 资源中心卡片(无设备数据依赖) /// 资源中心卡片(保持不变)
Widget _buildResourceCenterCard() { Widget _buildResourceCenterCard() {
return Container( return Container(
padding: const EdgeInsets.all(16), padding: const EdgeInsets.all(16),
decoration: BoxDecoration( decoration: BoxDecoration(
color: Colors.white, color: Colors.white,
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.1),
blurRadius: 8,
offset: const Offset(0, 2),
),
],
), ),
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
@@ -348,9 +403,9 @@ class _MachineDetailsPageState extends State<MachineDetailsPage> {
); );
} }
// 信息行组件(添加context必填参数) /// 通用信息行组件(保持不变)
Widget _buildInfoRow({ Widget _buildInfoRow({
required BuildContext context, // 必填的context参数 required BuildContext context,
required IconData icon, required IconData icon,
required String label, required String label,
required Widget trailing, required Widget trailing,
@@ -366,24 +421,35 @@ class _MachineDetailsPageState extends State<MachineDetailsPage> {
); );
} }
// 资源项组件 /// 资源项组件(保持不变)
Widget _buildResourceItem(String title, IconData icon) { Widget _buildResourceItem(String title, IconData icon) {
return Row( return InkWell(
children: [ onTap: () {
Icon(icon, size: 18, color: const Color(0xFF007AFF)), ScaffoldMessenger.of(
const SizedBox(width: 12), context,
Text(title, style: const TextStyle(fontSize: 16)), ).showSnackBar(SnackBar(content: Text('暂未开放$title功能')));
const Spacer(), },
const Icon(Icons.arrow_forward_ios, size: 16, color: Color(0xFF999999)), child: Row(
], children: [
Icon(icon, size: 18, color: const Color(0xFF007AFF)),
const SizedBox(width: 12),
Text(title, style: const TextStyle(fontSize: 16)),
const Spacer(),
const Icon(
Icons.arrow_forward_ios,
size: 16,
color: Color(0xFF999999),
),
],
),
); );
} }
// 解绑设备按钮 /// 解绑设备按钮(保持不变)
Widget _buildUnbindButton(BuildContext context) { Widget _buildUnbindButton(BuildContext context) {
return SizedBox( return SizedBox(
width: double.infinity, width: double.infinity,
height: 48, height: 50,
child: ElevatedButton( child: ElevatedButton(
style: ElevatedButton.styleFrom( style: ElevatedButton.styleFrom(
backgroundColor: Colors.white, backgroundColor: Colors.white,
@@ -391,49 +457,58 @@ class _MachineDetailsPageState extends State<MachineDetailsPage> {
shape: RoundedRectangleBorder( shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
), ),
side: const BorderSide(color: Color(0xFFFF3B30), width: 1),
padding: const EdgeInsets.symmetric(vertical: 8),
textStyle: const TextStyle(height: 1.2),
), ),
onPressed: () { onPressed: _isUpdatingName ? null : () => _showUnbindConfirmDialog(),
// 实现解绑逻辑
showDialog(
context: context,
builder: (dialogContext) => AlertDialog(
title: const Text('确认解绑'),
content: Text('确定要解绑【${_deviceName ?? '该设备'}】吗?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext),
child: const Text('取消'),
),
TextButton(
onPressed: _executeUnbind, // 执行解绑
//onPressed: () {
// //Navigator.pop(dialogContext);
// //context.read<DevicesCubit>().unbindDevice(
// // _deviceId ?? '',
// // _deviceName ?? '',
// //);
// // 执行解绑操作(传入设备ID)
// // _unbindDevice(device?.deviceName ?? '');
//},
child: const Text('确认'),
),
],
),
);
},
child: const Row( child: const Row(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [ children: [
Icon(Icons.unarchive_outlined, size: 18), Icon(Icons.unarchive_outlined, size: 18),
SizedBox(width: 12), SizedBox(width: 8),
Text('解绑设备', style: TextStyle(fontSize: 12)), Text(
'解绑设备',
style: TextStyle(fontSize: 16, height: 1.0),
overflow: TextOverflow.visible,
),
], ],
), ),
), ),
); );
} }
/// 显示解绑确认弹窗(保持不变)
void _showUnbindConfirmDialog() {
showDialog(
context: context,
builder: (dialogContext) {
_dialogContext = dialogContext;
return AlertDialog(
title: const Text('确认解绑'),
content: Text('确定要解绑【$_deviceName】吗?解绑后将无法管理该设备'),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext),
child: const Text('取消'),
),
TextButton(
style: TextButton.styleFrom(
foregroundColor: const Color(0xFFFF3B30),
),
onPressed: _executeUnbind,
child: const Text('确认'),
),
],
);
},
);
}
Future<void> _executeUnbind() async { Future<void> _executeUnbind() async {
if (_deviceId.isEmpty || _deviceName.isEmpty) { if (_deviceId.isEmpty || _deviceName.isEmpty) {
if (context.mounted) { if (context.mounted) {
@@ -447,70 +522,269 @@ class _MachineDetailsPageState extends State<MachineDetailsPage> {
return; return;
} }
// 调用 Cubit 解绑方法 // 关闭确认弹窗
await context.read<DevicesCubit>().unbindDevice(_deviceId, _deviceName);
}
/// 处理解绑结果(成功/失败)
void _handleUnbindResult(DevicesState state) {
// 1. 关闭确认弹窗
if (_dialogContext != null && Navigator.canPop(_dialogContext!)) { if (_dialogContext != null && Navigator.canPop(_dialogContext!)) {
Navigator.pop(_dialogContext!); Navigator.pop(_dialogContext!);
_dialogContext = null;
} }
// 2. 处理加载状态(隐藏加载弹窗/按钮禁用等) try {
if (state.isLoading) { // 显示加载弹窗并记录上下文
// 可选:显示加载弹窗 if (context.mounted) {
showDialog( showDialog(
context: context, context: context,
barrierDismissible: false, barrierDismissible: false,
builder: (ctx) => const AlertDialog( builder: (ctx) {
content: Row( _loadingDialogContext = ctx;
children: [ return const AlertDialog(
CircularProgressIndicator(), content: Row(
SizedBox(width: 16), children: [
Text("正在解绑设备..."), CircularProgressIndicator(strokeWidth: 2),
], SizedBox(width: 16),
Text("正在解绑设备..."),
],
),
);
},
);
}
// 调用Cubit解绑方法
await context.read<DevicesCubit>().unbindDevice(_deviceId, _deviceName);
// 主动关闭加载弹窗
if (_loadingDialogContext != null &&
Navigator.canPop(_loadingDialogContext!)) {
Navigator.pop(_loadingDialogContext!);
_loadingDialogContext = null;
}
} catch (e) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("解绑异常:${e.toString()}"),
backgroundColor: Colors.red,
), ),
), );
); // 关闭加载弹窗
if (_loadingDialogContext != null &&
Navigator.canPop(_loadingDialogContext!)) {
Navigator.pop(_loadingDialogContext!);
_loadingDialogContext = null;
}
}
}
}
/// 执行修改设备名称(核心修改:新增兜底逻辑)
Future<void> _executeUpdateDeviceName(String newDeviceName) async {
// 基础校验
if (_deviceId.isEmpty || newDeviceName.isEmpty) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text("设备信息异常,无法修改名称"),
backgroundColor: Colors.red,
),
);
}
setState(() => _isUpdatingName = false);
return; return;
} }
// 3. 处理结果 try {
if (state.errorMessage?.isEmpty == true) { // 显示加载弹窗并记录专属上下文
// 解绑成功 if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar( showDialog(
SnackBar( context: context,
content: Text("设备「$_deviceName」解绑成功"), barrierDismissible: false,
backgroundColor: Colors.green, builder: (ctx) {
duration: const Duration(seconds: 2), _updateLoadingContext = ctx;
), return const AlertDialog(
content: Row(
children: [
CircularProgressIndicator(strokeWidth: 2),
SizedBox(width: 16),
Text("正在修改名称..."),
],
),
);
},
);
}
print(
"调用updateDeviceName,deviceId: $_deviceId, newDeviceName: $newDeviceName",
);
// 调用Cubit修改方法
await context.read<DevicesCubit>().updateDeviceName(
_deviceId,
newDeviceName,
); );
// 延迟返回上一页(让用户看到提示) // 主动关闭修改名称加载弹窗
Future.delayed(const Duration(seconds: 1), () { if (_updateLoadingContext != null &&
if (context.mounted) { Navigator.canPop(_updateLoadingContext!)) {
Navigator.pop(context); // 返回设备列表页 Navigator.pop(_updateLoadingContext!);
_updateLoadingContext = null;
}
// 主动重置更新状态
setState(() => _isUpdatingName = false);
// 兜底:强制将Cubit的isLoading置为false
if (context.mounted) {
context.read<DevicesCubit>().emit(
context.read<DevicesCubit>().state.copyWith(
isLoading: false,
operationType: DeviceOperationType.none,
),
);
}
} catch (e) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("修改异常:${e.toString()}"),
backgroundColor: Colors.red,
),
);
// 关闭修改名称加载弹窗
if (_updateLoadingContext != null &&
Navigator.canPop(_updateLoadingContext!)) {
Navigator.pop(_updateLoadingContext!);
_updateLoadingContext = null;
} }
}); }
} else if (state.errorMessage?.isNotEmpty == true) { setState(() => _isUpdatingName = false);
// 解绑失败
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("解绑失败:${state.errorMessage ?? '未知错误'}"),
backgroundColor: Colors.red,
),
);
// 关闭加载弹窗(如果存在) // 兜底:强制重置Cubit的loading状态
if (Navigator.canPop(context)) { if (context.mounted) {
Navigator.pop(context); context.read<DevicesCubit>().emit(
context.read<DevicesCubit>().state.copyWith(
isLoading: false,
operationType: DeviceOperationType.none,
),
);
}
}
}
/// 处理解绑结果(保持不变)
void _handleUnbindResult(DevicesState state) {
// 强制关闭加载弹窗
if (_loadingDialogContext != null &&
Navigator.canPop(_loadingDialogContext!)) {
Navigator.pop(_loadingDialogContext!);
_loadingDialogContext = null;
} else if (!state.isLoading &&
context.mounted &&
Navigator.canPop(context)) {
Navigator.pop(context);
}
if (state.errorMessage?.isEmpty == true && !state.isLoading) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("设备「$_deviceName」解绑成功"),
backgroundColor: Colors.green,
duration: const Duration(seconds: 2),
),
);
final username =
context.read<AppUserCubit>().state.user?.username ?? "";
context.read<DevicesCubit>().fetchAllDevices(username);
}
} else if (state.errorMessage?.isNotEmpty == true && !state.isLoading) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("解绑失败:${state.errorMessage ?? '未知错误'}"),
backgroundColor: Colors.red,
),
);
} }
} }
final username = context.read<AppUserCubit>().state.user?.username ?? "";
context.read<DevicesCubit>().fetchAllDevices(username);
context.go(RoutePaths.home); context.go(RoutePaths.home);
} }
/// 处理修改名称结果(核心修改:放宽判断条件)
void _handleUpdateNameResult(DevicesState state) {
// 强制关闭修改名称加载弹窗(优先用专属上下文)
if (_updateLoadingContext != null &&
Navigator.canPop(_updateLoadingContext!)) {
Navigator.pop(_updateLoadingContext!);
_updateLoadingContext = null;
}
// 兜底:兼容旧逻辑
else if (context.mounted && Navigator.canPop(context)) {
// 不管loading状态,只要弹窗存在就关闭
Navigator.pop(context);
}
// 处理结果:放宽条件,只要无错误信息就认为成功(不管loading)
print(
"处理修改名称结果,operationType: ${state.operationType}, isLoading: ${state.isLoading}, errorMessage: ${state.errorMessage},state.errorMessage?.isEmpty: ${state.errorMessage?.isEmpty}",
);
// 核心修改:去掉!state.isLoading的判断
if (state.errorMessage?.isEmpty == true) {
setState(() {
_deviceName = _nameController.text.trim();
_isUpdatingName = false; // 双重保障重置状态
});
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("设备名称已修改为:$_deviceName"),
backgroundColor: Colors.green,
duration: const Duration(seconds: 2),
),
);
// 关闭修改名称的底部抽屉(如果还在)
if (_editNameSheetContext != null &&
Navigator.canPop(_editNameSheetContext!)) {
Navigator.pop(_editNameSheetContext!);
_editNameSheetContext = null;
}
// 强制重置Cubit的loading状态
context.read<DevicesCubit>().emit(
state.copyWith(
isLoading: false,
operationType: DeviceOperationType.none,
),
);
}
} else if (state.errorMessage?.isNotEmpty == true) {
setState(() => _isUpdatingName = false);
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("修改失败:${state.errorMessage ?? '未知错误'}"),
backgroundColor: Colors.red,
),
);
// 强制重置Cubit的loading状态
context.read<DevicesCubit>().emit(
state.copyWith(
isLoading: false,
operationType: DeviceOperationType.none,
),
);
}
}
}
/// 复制到剪贴板(保持不变)
void _copyToClipboard(String text, String tip) {
Clipboard.setData(ClipboardData(text: text));
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(tip), duration: const Duration(seconds: 1)),
);
}
}
} }