Author SHA1 Message Date
linfeng 0c1fb24685 update 2026-07-29 18:47:45 +08:00
linfeng a849457172 点击录新选手返回扫码页 2026-07-29 18:22:37 +08:00
linfeng d6a7e74809 Merge branch 'linfeng/drone_scoring/dev_1.1.0/2026630' into linfeng/drone_video/dev_1.1.0/20260707 2026-07-29 18:12:12 +08:00
linfeng df38ecee18 登录后清空输入框 2026-07-29 18:06:53 +08:00
linfeng 9dea31f76e Merge branch 'linfeng/drone_scoring/dev_1.1.0/2026630' into linfeng/drone_video/dev_1.1.0/20260707 2026-07-29 18:01:06 +08:00
linfeng 7faa8e5c47 更新获取赛事列表功能,增加 NAS IP 地址参数以支持动态请求 2026-07-29 18:00:45 +08:00
linfeng 17799af2e7 Merge branch 'linfeng/drone_scoring/dev_1.1.0/2026630' into linfeng/drone_video/dev_1.1.0/20260707 2026-07-29 11:51:21 +08:00
linfeng 7d65be0514 选手赛项列表增加 选手与该赛项的选手编号属性 2026-07-29 11:51:11 +08:00
linfeng d4920e2b98 1.录像页面,根据个人赛和团队赛 动态 录像页标题
2.录像结束弹窗按钮文本修改
2026-07-29 11:18:58 +08:00
linfeng a19d9dfa6d Merge branch 'linfeng/drone_scoring/dev_1.1.0/2026630' into linfeng/drone_video/dev_1.1.0/20260707 2026-07-29 10:15:25 +08:00
linfeng 40799f2d15 扫码页支持返回上一页 2026-07-29 10:13:47 +08:00
linfeng 934b3ea2fa Merge branch 'linfeng/drone_scoring/dev_1.1.0/2026630' into linfeng/drone_video/dev_1.1.0/20260707 2026-07-29 09:19:19 +08:00
linfeng f7f7413b55 优化扫码页 UI 2026-07-28 18:50:14 +08:00
linfeng 8e599f5a86 完成视频播放UI 调整 2026-07-28 18:02:40 +08:00
linfeng 9fca76f679 1.完成查看录像模块功能
2.完成录像页面播放视频功能
2026-07-28 16:36:32 +08:00
linfeng a324825e8a update 2026-07-28 15:46:52 +08:00
linfeng 6793ca53af 还原参赛队伍列表页、详情页 2026-07-28 15:46:23 +08:00
linfeng 9e72bc522e 解决查看录像页 UI 2026-07-28 14:59:34 +08:00
linfeng 36253aacbe 优化录制页性能 2026-07-28 13:47:25 +08:00
linfeng 1096645e79 update git 湖绿 2026-07-28 12:04:28 +08:00
linfeng a56a42c7c8 1.修改文案
2.副裁 APP 不需要查看参赛队伍
2026-07-28 12:00:16 +08:00
33 changed files with 1576 additions and 596 deletions
+1 -1
View File
@@ -51,4 +51,4 @@ app.*.map.json
CLAUDE.md
AGENTS.md
test/
script/
script/
Binary file not shown.

After

Width:  |  Height:  |  Size: 148 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

+1 -1
View File
@@ -5,4 +5,4 @@ flutter build apk --release --split-per-abi
# echo "构建完成时间: $(date '+%Y-%m-%d %H:%M:%S')"
pgyer upload build/app/outputs/flutter-apk/app-arm64-v8a-release.apk --build-update-description "新增可视化请求插件"
pgyer upload build/app/outputs/flutter-apk/app-arm64-v8a-release.apk --build-update-description "副裁判 APP $(date '+%Y-%m-%d %H:%M:%S')"
+3
View File
@@ -17,6 +17,9 @@ enum AuthApi {
/// 人工设置晋级/淘汰
setTeamStatus('/api/events/device/schedule/team/score'),
/// 获取登录设备信息
getLoginDeviceInfo('/api/events/device/nas/info'),
/// 获取选手的赛事信息
playerRegistrationList('/api/events/device/player/registration/list');
+17 -3
View File
@@ -38,11 +38,15 @@ class ApiClient {
return _parseData<T>(raw, parser);
}
if (raw is! Map<String, dynamic>) {
final payload = raw is Map ? Map<String, dynamic>.from(raw) : null;
if (payload == null ||
!(payload.containsKey('code') || payload.containsKey('message'))) {
return _parseData<T>(raw, parser);
}
final wrapped = ApiResponse<T>.fromJson(raw, fromJsonT: parser);
// 先按 {code,message,data} 解包,再用业务 parser 解析 data
// 避免把 Map 直接强转成业务模型。
final wrapped = ApiResponse<dynamic>.fromJson(payload);
if (!wrapped.isSuccess) {
throw ApiException(
code: wrapped.code,
@@ -52,7 +56,17 @@ class ApiClient {
);
}
return wrapped.data as T;
if (wrapped.data == null) {
if (null is T) return null as T;
throw ApiException(
code: wrapped.code,
statusCode: response.statusCode,
message: '响应 data 为空',
details: raw,
);
}
return _parseData<T>(wrapped.data, parser);
} on DioException catch (error) {
throw _mapDioException(error);
}
+17 -1
View File
@@ -11,10 +11,26 @@ class ApiResponse<T> {
Map<String, dynamic> json, {
T Function(dynamic json)? fromJsonT,
}) {
final rawData = json['data'];
T? data;
if (rawData != null && fromJsonT != null) {
data = fromJsonT(rawData);
} else if (rawData != null && fromJsonT == null) {
// 无 parser 时仅在类型已匹配时接收,避免 Map 被强转为业务模型。
if (rawData is T) {
data = rawData;
} else {
throw FormatException(
'ApiResponse data 类型不匹配,且未提供 fromJsonT;'
'期望 $T,实际 ${rawData.runtimeType}',
);
}
}
return ApiResponse<T>(
code: (json['code'] as num?)?.toInt() ?? 200,
message: (json['message'] ?? json['msg'] ?? '').toString(),
data: fromJsonT == null ? json['data'] as T? : fromJsonT(json['data']),
data: data,
);
}
}
+22 -9
View File
@@ -22,15 +22,20 @@ class GetRecordListResModel {
GetRecordListResModel({this.path, this.items});
factory GetRecordListResModel.fromJson(Map<String, dynamic> json) =>
GetRecordListResModel(
path: json['path'],
items: json['items'] == null
? []
: List<RecordListItem>.from(
json['items']!.map((x) => RecordListItem.fromJson(x)),
),
);
factory GetRecordListResModel.fromJson(Map<String, dynamic> json) {
final rawItems = json['items'];
return GetRecordListResModel(
path: json['path']?.toString(),
items: rawItems is! List
? []
: rawItems
.whereType<Map>()
.map(
(x) => RecordListItem.fromJson(Map<String, dynamic>.from(x)),
)
.toList(),
);
}
Map<String, dynamic> toJson() => {
'path': path,
@@ -40,6 +45,14 @@ class GetRecordListResModel {
};
}
enum RecordItemType {
file('file'),
directory('dir');
final String value;
const RecordItemType(this.value);
}
class RecordListItem {
String? name;
String? path;
+4
View File
@@ -18,6 +18,7 @@ class JwtDecodedData {
String? oId;
List<String>? oIds;
String? organizerId;
String? nasIpAddr;
JwtDecodedData({
this.authType,
@@ -28,6 +29,7 @@ class JwtDecodedData {
this.oId,
this.oIds,
this.organizerId,
this.nasIpAddr,
});
factory JwtDecodedData.fromJson(Map<String, dynamic> json) => JwtDecodedData(
@@ -41,6 +43,7 @@ class JwtDecodedData {
? []
: List<String>.from(json['oIds']!.map((x) => x?.toString())),
organizerId: json['organizerId']?.toString(),
nasIpAddr: json['nasIpAddr']?.toString(),
);
Map<String, dynamic> toJson() => {
@@ -52,6 +55,7 @@ class JwtDecodedData {
'oId': oId,
'oIds': oIds == null ? [] : List<dynamic>.from(oIds!.map((x) => x)),
'organizerId': organizerId,
'nasIpAddr': nasIpAddr,
};
}
+41 -21
View File
@@ -12,7 +12,6 @@ import 'package:recording_tool/core/utils/util_search_nasIp.dart';
import 'package:recording_tool/features/auth/view_model_auth/view_model_auth.dart';
import 'package:recording_tool/features/scan_qrcode/pages/page_scan_qrcode.dart';
import 'package:recording_tool/gen/assets.gen.dart';
import 'package:recording_tool/shared/widgets/app_button.dart';
import 'package:recording_tool/shared/widgets/app_dialog.dart';
import 'package:recording_tool/shared/widgets/app_toast.dart';
@@ -26,10 +25,12 @@ class AuthPageWidget extends ConsumerStatefulWidget {
class _AuthPageWidgetState extends ConsumerState<AuthPageWidget> {
late final TextEditingController _controller;
/// 记录点击次数
int _clickCount = 0;
@override
void initState() {
super.initState();
_controller = TextEditingController(text: '999779');
_controller = TextEditingController(text: '');
WidgetsBinding.instance.addPostFrameCallback((_) async {
// 静默探测 NAS,不阻塞登录 / 自动跳转
@@ -37,6 +38,12 @@ class _AuthPageWidgetState extends ConsumerState<AuthPageWidget> {
final token = AppStorage.getString(StorageKeys.authToken);
if (token?.isNotEmpty ?? false) {
final success = await ref
.read(authProvider.notifier)
.parseTokenSetState();
if (!success) {
return;
}
AppNavigator.push(const ScanQrCodePage());
}
});
@@ -48,6 +55,12 @@ class _AuthPageWidgetState extends ConsumerState<AuthPageWidget> {
super.dispose();
}
void _showDeviceCodeDialog() async {
final deviceCode = await DeviceUtils.deviceCode();
if (!mounted) return;
AppDialog.confirm(context, title: '设备码:$deviceCode');
}
@override
Widget build(BuildContext context) {
final authState = ref.watch(authProvider);
@@ -61,14 +74,11 @@ class _AuthPageWidgetState extends ConsumerState<AuthPageWidget> {
backgroundColor: Colors.white,
body: Stack(
children: [
Positioned(
top: 0,
left: 0,
right: 0,
Positioned.fill(
child: Image.asset(
_AuthAssets.pageBg,
width: double.infinity,
fit: BoxFit.fitWidth,
fit: BoxFit.fill,
),
),
SafeArea(
@@ -80,11 +90,20 @@ class _AuthPageWidgetState extends ConsumerState<AuthPageWidget> {
SizedBox(height: 190.h),
ClipRRect(
borderRadius: BorderRadius.circular(24.r),
child: Image.asset(
_AuthAssets.appIcon,
width: 82.w,
height: 82.w,
fit: BoxFit.cover,
child: GestureDetector(
onTap: () {
_clickCount++;
if (_clickCount >= 5) {
_showDeviceCodeDialog();
_clickCount = 0;
}
},
child: Image.asset(
_AuthAssets.appIcon,
width: 82.w,
height: 82.w,
fit: BoxFit.cover,
),
),
),
SizedBox(height: 18.h),
@@ -101,15 +120,15 @@ class _AuthPageWidgetState extends ConsumerState<AuthPageWidget> {
isLoading: authState.isLoading,
onPressed: _handleSubmit,
),
SizedBox(height: 20.h),
AppButton(
onPressed: () async {
final deviceCode = await DeviceUtils.deviceCode();
if (!mounted) return;
AppDialog.confirm(context, title: '设备码:$deviceCode');
},
label: '获取设备码',
),
// SizedBox(height: 20.h),
// AppButton(
// onPressed: () async {
// final deviceCode = await DeviceUtils.deviceCode();
// if (!mounted) return;
// AppDialog.confirm(context, title: '设备码:$deviceCode');
// },
// label: '获取设备码',
// ),
],
),
),
@@ -127,6 +146,7 @@ class _AuthPageWidgetState extends ConsumerState<AuthPageWidget> {
.auth(_controller.text);
if (!mounted) return;
if (success) {
_controller.clear();
AppNavigator.push(const ScanQrCodePage());
return;
}
+52 -12
View File
@@ -1,8 +1,10 @@
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:recording_tool/app/config/api_common.dart';
import 'package:recording_tool/core/network/providers/dio_providers.dart';
import 'package:recording_tool/core/utils/device_utils.dart';
import 'package:recording_tool/features/auth/model/model_auth.dart';
import 'package:recording_tool/features/auth/model/model_jwt.dart';
class AuthServer {
/// [passCode] 口令码
@@ -28,17 +30,55 @@ class AuthServer {
/// 获取赛事列表
/// [path] 赛事目录
static Future<GetRecordListResModel> getRecordList(
Ref ref,
String path,
) async {
final apiClient = ref.read(apiClientProvider);
final data = await apiClient.get<GetRecordListResModel>(
'http://sheling.local:9001/${AuthApi.getRecordList.path}',
queryParameters: {'path': path},
parser: (json) =>
GetRecordListResModel.fromJson(json as Map<String, dynamic>),
);
return data;
/// [nasIpAddr] NAS IP,由调用方传入,避免在 authProvider 内部再 read(authProvider)。
static Future<GetRecordListResModel?> getRecordList(
Ref ref, {
required String path,
required String nasIpAddr,
}) async {
try {
if (nasIpAddr.isEmpty) {
throw const FormatException('无法获取NAS IP地址');
}
final apiClient = ref.read(apiClientProvider);
// NAS /api/files 直接返回 {path, items},不是业务网关的 {code,message,data} 包装。
final data = await apiClient.get<GetRecordListResModel>(
'http://$nasIpAddr:9001/${AuthApi.getRecordList.path}',
queryParameters: {'path': path},
wrapResponse: false,
parser: (json) {
if (json is! Map) {
throw const FormatException('录像列表响应格式错误');
}
return GetRecordListResModel.fromJson(
Map<String, dynamic>.from(json),
);
},
);
return data;
} catch (error) {
debugPrint('getRecordList failed: $error');
return null;
}
}
/// 获取登录设备信息
static Future<JwtDecodedData?> getLoginDeviceInfo(Ref ref) async {
try {
final apiClient = ref.read(apiClientProvider);
final data = await apiClient.get<JwtDecodedData>(
AuthApi.getLoginDeviceInfo.path,
parser: (json) {
if (json is! Map) {
throw const FormatException('登录设备信息响应格式错误');
}
return JwtDecodedData.fromJson(Map<String, dynamic>.from(json));
},
);
return data;
} catch (error) {
debugPrint('getLoginDeviceInfo failed: $error');
return null;
}
}
}
+1
View File
@@ -28,6 +28,7 @@ class AuthState {
isLoading: isLoading ?? this.isLoading,
errorMessage: errorMessage ?? this.errorMessage,
jwtDecodedData: jwtDecodedData ?? this.jwtDecodedData,
recordList: recordList ?? this.recordList,
);
}
}
@@ -1,11 +1,9 @@
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_riverpod/legacy.dart';
import 'package:jwt_decoder/jwt_decoder.dart';
import 'package:recording_tool/core/cache/app_storage.dart';
import 'package:recording_tool/core/cache/storage_keys.dart';
import 'package:recording_tool/core/network/api_exception.dart';
import 'package:recording_tool/features/auth/model/model_jwt.dart';
import 'package:recording_tool/features/auth/model/model_auth.dart';
import 'package:recording_tool/features/auth/server/server_auth.dart';
import 'package:recording_tool/features/auth/state/state_auth.dart';
@@ -32,7 +30,11 @@ class AuthViewModel extends StateNotifier<AuthState> {
await AppStorage.setString(StorageKeys.authToken, data.deviceAccessToken);
state = const AuthState();
if (data.deviceAccessToken.isNotEmpty) {
parseTokenSetState(data.deviceAccessToken);
final ok = await parseTokenSetState();
if (!ok) {
state = const AuthState(errorMessage: '获取赛事信息失败,请重试');
return false;
}
}
return true;
} on FormatException catch (error) {
@@ -48,29 +50,53 @@ class AuthViewModel extends StateNotifier<AuthState> {
}
/// 解析 TOKEN,并更新状态
Future<bool> parseTokenSetState(String token) async {
final decoded = JwtDecoder.decode(token);
final rawData = decoded['data'];
if (rawData is! Map) return false;
try {
final data = JwtDecodedData.fromJson(Map<String, dynamic>.from(rawData));
state = state.copyWith(jwtDecodedData: data);
return true;
} catch (error) {
debugPrint('认证失败,请重试: $error');
return false;
}
Future<bool> parseTokenSetState() async {
final data = await AuthServer.getLoginDeviceInfo(_ref);
if (data == null) return false;
state = state.copyWith(jwtDecodedData: data);
return true;
// final decoded = JwtDecoder.decode(token);
// final rawData = decoded['data'];
// if (rawData is! Map) return false;
// try {
// final data = JwtDecodedData.fromJson(Map<String, dynamic>.from(rawData));
// state = state.copyWith(jwtDecodedData: data);
// return true;
// } catch (error) {
// debugPrint('认证失败,请重试: $error');
// return false;
// }
}
/// 获取赛事列表
Future<bool> getRecordList(String eventName) async {
if (eventName.isEmpty) return false;
final data = await AuthServer.getRecordList(_ref, eventName);
if (data.items == null || data.items!.isEmpty) return false;
final nasIpAddr = state.jwtDecodedData?.nasIpAddr?.trim() ?? '';
if (nasIpAddr.isEmpty) return false;
final data = await AuthServer.getRecordList(
_ref,
path: eventName,
nasIpAddr: nasIpAddr,
);
if (data == null) return false;
if (data.items == null) return false;
state = state.copyWith(recordList: data.items);
return true;
}
/// 获取指定目录的录像列表(不更新 state,用于目录下钻)
Future<List<RecordListItem>?> fetchRecordList(String path) async {
if (path.isEmpty) return null;
final nasIpAddr = state.jwtDecodedData?.nasIpAddr?.trim() ?? '';
if (nasIpAddr.isEmpty) return null;
final data = await AuthServer.getRecordList(
_ref,
path: path,
nasIpAddr: nasIpAddr,
);
return data?.items;
}
/// 清空授权信息(本地 token + 内存状态)
Future<void> clearAuth() async {
await AppStorage.remove(StorageKeys.authToken);
@@ -7,6 +7,8 @@ import 'package:recording_tool/features/competition_teams/model/model_competitio
import 'package:recording_tool/features/competition_teams/widgets/widget_manual_winner_dialog.dart';
import 'package:recording_tool/features/events/request_model/request_model_event.dart';
import 'package:recording_tool/features/events/server/server_events.dart';
import 'package:recording_tool/gen/assets.gen.dart';
import 'package:recording_tool/shared/widgets/app_bar.dart';
import 'package:recording_tool/shared/widgets/app_empty_view.dart';
import 'package:recording_tool/shared/widgets/app_toast.dart';
@@ -79,14 +81,14 @@ class _CompetitionTeamDetailPageState
final matchups = _matchups;
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(title: Text(_title)),
backgroundColor: const Color(0xFFF2F4F7),
appBar: AppPageBar(title: _title),
body: matchups.isEmpty
? const AppEmptyView(message: '暂无对阵信息')
: ListView.separated(
padding: EdgeInsets.fromLTRB(20.w, 24.h, 20.w, 36.h),
padding: EdgeInsets.only(bottom: 36.h),
itemCount: matchups.length,
separatorBuilder: (_, _) => SizedBox(height: 22.h),
separatorBuilder: (_, _) => SizedBox(height: 12.h),
itemBuilder: (context, index) {
final raw = matchups[index];
final matchup = _toCompetitionMatchup(raw, index);
@@ -95,8 +97,6 @@ class _CompetitionTeamDetailPageState
}
return _MatchupCard(
matchup: matchup,
index: index,
matchTitle: raw.matchTitle?.trim() ?? '',
onManualProcess: () => _handleManualProcess(raw, index),
);
},
@@ -175,91 +175,74 @@ class _CompetitionTeamDetailPageState
}
class _MatchupCard extends StatelessWidget {
const _MatchupCard({
required this.matchup,
required this.index,
required this.matchTitle,
required this.onManualProcess,
});
const _MatchupCard({required this.matchup, required this.onManualProcess});
/// 背景图 image_team_vs_bg.png 的原始宽高比(1920 x 318)。
static const double _vsBgAspectRatio = 1920 / 318;
final CompetitionMatchup matchup;
final int index;
final String matchTitle;
final VoidCallback onManualProcess;
@override
Widget build(BuildContext context) {
final title = matchTitle.isEmpty ? '${index + 1}' : matchTitle;
return Container(
key: ValueKey('competition-matchup-${matchup.id}'),
padding: EdgeInsets.fromLTRB(16.w, 10.h, 16.w, 18.h),
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(color: const Color(0xFFC7CCD4)),
borderRadius: BorderRadius.circular(12.r),
),
color: Colors.white,
padding: EdgeInsets.fromLTRB(12.w, 4.h, 12.w, 24.h),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Expanded(
child: Text(
title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 14.sp,
color: const Color(0xFF7A828E),
),
Align(
alignment: Alignment.centerRight,
child: TextButton(
key: ValueKey('manual-process-${matchup.id}'),
onPressed: onManualProcess,
style: TextButton.styleFrom(
padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
minimumSize: Size.zero,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
child: Text(
'人工处理',
style: TextStyle(
fontSize: 15.sp,
fontWeight: FontWeight.w500,
color: const Color(0xFF078AF2),
),
),
TextButton(
key: ValueKey('manual-process-${matchup.id}'),
onPressed: onManualProcess,
child: Text(
'人工处理',
style: TextStyle(
fontSize: 17.sp,
fontWeight: FontWeight.w600,
color: const Color(0xFF078AF2),
),
),
),
],
),
),
SizedBox(height: 8.h),
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: _TeamPanel(
team: matchup.teamA,
alignment: CrossAxisAlignment.start,
winner: matchup.winnerTeamId == matchup.teamA.id,
accentColor: const Color(0xFFFF6B75),
AspectRatio(
aspectRatio: _vsBgAspectRatio,
child: DecoratedBox(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(Assets.images.imageTeamVsBg.path),
fit: BoxFit.fill,
),
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 12.w),
child: Text(
'VS',
style: TextStyle(
fontSize: 21.sp,
fontWeight: FontWeight.w700,
color: const Color(0xFF303640),
child: Row(
children: [
Expanded(
child: _TeamPanel(
team: matchup.teamA,
isLeft: true,
winner: matchup.winnerTeamId == matchup.teamA.id,
accentColor: const Color(0xFFFF6B75),
),
),
),
Expanded(
child: _TeamPanel(
team: matchup.teamB,
isLeft: false,
winner: matchup.winnerTeamId == matchup.teamB.id,
accentColor: const Color(0xFF12A6C8),
),
),
],
),
Expanded(
child: _TeamPanel(
team: matchup.teamB,
alignment: CrossAxisAlignment.end,
textAlign: TextAlign.end,
winner: matchup.winnerTeamId == matchup.teamB.id,
accentColor: const Color(0xFF20BFA9),
),
),
],
),
),
],
),
@@ -270,83 +253,72 @@ class _MatchupCard extends StatelessWidget {
class _TeamPanel extends StatelessWidget {
const _TeamPanel({
required this.team,
required this.alignment,
required this.isLeft,
required this.winner,
required this.accentColor,
this.textAlign = TextAlign.start,
});
final CompetitionTeam team;
final CrossAxisAlignment alignment;
final TextAlign textAlign;
/// 左半区(红色面板,右对齐、略偏上);右半区(蓝色面板,左对齐、略偏下)。
final bool isLeft;
final bool winner;
final Color accentColor;
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: alignment,
final textAlign = isLeft ? TextAlign.end : TextAlign.start;
final nameRow = Row(
mainAxisSize: MainAxisSize.min,
children: [
AnimatedContainer(
duration: const Duration(milliseconds: 180),
padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
decoration: BoxDecoration(
color: winner
? accentColor.withValues(alpha: 0.14)
: Colors.transparent,
borderRadius: BorderRadius.circular(8.r),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Flexible(
child: Text(
team.name,
textAlign: textAlign,
style: TextStyle(
fontSize: 18.sp,
fontWeight: FontWeight.w600,
color: const Color(0xFF282E37),
),
),
),
if (winner) ...[
SizedBox(width: 5.w),
Icon(Icons.emoji_events, size: 17.r, color: accentColor),
],
],
),
),
SizedBox(height: 10.h),
Text(
team.playerNames,
textAlign: textAlign,
style: TextStyle(
fontSize: 15.sp,
height: 1.45,
color: const Color(0xFF4E5662),
Flexible(
child: Text(
team.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
textAlign: textAlign,
style: TextStyle(
fontSize: 15.sp,
fontWeight: FontWeight.w600,
color: const Color(0xFF282E37),
),
),
),
if (winner) ...[
SizedBox(height: 8.h),
Container(
SizedBox(width: 4.w),
Icon(
Icons.emoji_events,
key: ValueKey('winner-${team.id}'),
padding: EdgeInsets.symmetric(horizontal: 9.w, vertical: 3.h),
decoration: BoxDecoration(
color: accentColor,
borderRadius: BorderRadius.circular(10.r),
),
child: Text(
'胜方',
style: TextStyle(
fontSize: 12.sp,
fontWeight: FontWeight.w700,
color: Colors.white,
),
),
size: 14.r,
color: accentColor,
),
],
],
);
return Padding(
// 中线两侧留出 VS 图案空间,外侧避开斜切边缘。
padding: isLeft
? EdgeInsets.only(left: 16.w, right: 30.w, bottom: 10.h)
: EdgeInsets.only(left: 30.w, right: 16.w, top: 10.h),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: isLeft
? CrossAxisAlignment.end
: CrossAxisAlignment.start,
children: [
nameRow,
SizedBox(height: 4.h),
Text(
team.playerNames,
maxLines: 1,
overflow: TextOverflow.ellipsis,
textAlign: textAlign,
style: TextStyle(fontSize: 13.sp, color: const Color(0xFF4E5662)),
),
],
),
);
}
}
@@ -6,6 +6,7 @@ import 'package:recording_tool/features/competition_teams/model/model_competitio
import 'package:recording_tool/features/competition_teams/pages/page_competition_team_detail.dart';
import 'package:recording_tool/features/competition_teams/server/server_competition_teams.dart';
import 'package:recording_tool/features/competition_teams/view_model/view_model_competition_teams.dart';
import 'package:recording_tool/shared/widgets/app_bar.dart';
import 'package:recording_tool/shared/widgets/app_empty_view.dart';
import 'package:recording_tool/shared/widgets/app_error_view.dart';
import 'package:recording_tool/shared/widgets/app_loading_view.dart';
@@ -34,8 +35,8 @@ class _CompetitionTeamListPageState
Widget build(BuildContext context) {
final state = ref.watch(competitionTeamsProvider);
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(title: const Text('参赛队伍')),
backgroundColor: const Color(0xFFF5F6F8),
appBar: AppPageBar(title: '参赛队伍'),
body: SafeArea(
top: false,
child: Builder(
@@ -56,8 +57,8 @@ class _CompetitionTeamListPageState
onRefresh: ref.read(competitionTeamsProvider.notifier).refresh,
onLoadMore: ref.read(competitionTeamsProvider.notifier).loadMore,
enablePullUp: state.hasMore,
padding: EdgeInsets.fromLTRB(20.w, 18.h, 20.w, 28.h),
separator: SizedBox(height: 14.h),
padding: EdgeInsets.fromLTRB(10.w, 10.h, 10.w, 24.h),
separator: SizedBox(height: 8.h),
empty: const AppEmptyView(message: '暂无参赛队伍'),
itemBuilder: (context, item, index) {
return _CompetitionScheduleCard(
@@ -97,33 +98,26 @@ class _CompetitionScheduleCard extends StatelessWidget {
@override
Widget build(BuildContext context) {
final scheduleText = item.scheduleTime.isEmpty ? '时间待定' : item.scheduleTime;
return Material(
key: ValueKey('competition-team-item-${item.itemId}'),
color: Colors.white,
borderRadius: BorderRadius.circular(14.r),
borderRadius: BorderRadius.circular(6.r),
child: InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(14.r),
borderRadius: BorderRadius.circular(6.r),
child: Container(
constraints: BoxConstraints(minHeight: 142.h),
padding: EdgeInsets.all(16.r),
constraints: BoxConstraints(minHeight: 86.h),
padding: EdgeInsets.fromLTRB(12.w, 10.h, 14.w, 10.h),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(14.r),
border: Border.all(color: const Color(0xFFD7DBE2)),
boxShadow: const [
BoxShadow(
color: Color(0x0F1A2230),
blurRadius: 16,
offset: Offset(0, 6),
),
],
color: Colors.white,
borderRadius: BorderRadius.circular(6.r),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
@@ -131,23 +125,21 @@ class _CompetitionScheduleCard extends StatelessWidget {
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 19.sp,
fontWeight: FontWeight.w600,
color: const Color(0xFF20242B),
fontSize: 13.sp,
height: 1.2,
color: const Color(0xFF30343A),
fontWeight: FontWeight.w700,
),
),
SizedBox(height: 18.h),
_InfoLine(
icon: Icons.schedule_outlined,
text: scheduleText,
),
SizedBox(height: 6.h),
_MetaText(_formatScheduleTime(item)),
],
),
),
SizedBox(width: 14.w),
SizedBox(width: 12.w),
Icon(
Icons.chevron_right,
size: 28.r,
size: 20.r,
color: const Color(0xFF9AA3AF),
),
],
@@ -158,27 +150,40 @@ class _CompetitionScheduleCard extends StatelessWidget {
}
}
class _InfoLine extends StatelessWidget {
const _InfoLine({required this.icon, required this.text});
class _MetaText extends StatelessWidget {
const _MetaText(this.text);
final IconData icon;
final String text;
@override
Widget build(BuildContext context) {
return Row(
children: [
Icon(icon, size: 18.r, color: const Color(0xFF7B8491)),
SizedBox(width: 8.w),
Expanded(
child: Text(
text,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 15.sp, color: const Color(0xFF525B68)),
),
),
],
return Text(
text,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 10.sp,
height: 1.2,
color: const Color(0xFF6E747D),
fontWeight: FontWeight.w400,
),
);
}
}
String _formatScheduleTime(CompetitionTeamListItem item) {
final start = DateTime.tryParse(item.matchStartTime);
final end = DateTime.tryParse(item.matchEndTime);
if (start == null && end == null) {
return item.scheduleTime.isEmpty ? '时间待定' : item.scheduleTime;
}
if (start != null && end != null) {
return '${start.month}${start.day}${_formatClock(start)}-${_formatClock(end)}';
}
final value = start ?? end!;
return '${value.month}${value.day}${_formatClock(value)}';
}
String _formatClock(DateTime value) {
return '${value.hour}:${value.minute.toString().padLeft(2, '0')}';
}
@@ -134,6 +134,7 @@ class EventRegistrationItem {
required this.itemName,
required this.groupName,
required this.matchPlace,
this.matchStartTime = '',
this.matchEndTime = '',
this.completed = false,
@@ -143,6 +144,7 @@ class EventRegistrationItem {
this.userId = '',
this.playerName = '',
this.playerPhone = '',
this.playerNo = '',
});
final String eventId;
@@ -158,6 +160,7 @@ class EventRegistrationItem {
final String opponentId;
final String opponentName;
final List<EventTeamMember> teamMembers;
final String playerNo;
/// 来自报名列表父级,不在 item JSON 内
final String userId;
@@ -205,6 +208,7 @@ class EventRegistrationItem {
: const [],
userId: userId,
playerName: playerName,
playerNo: _readString(map, const ['playerNo']),
);
}
+18 -9
View File
@@ -2,7 +2,6 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:recording_tool/app/config/app_config.dart';
import 'package:recording_tool/app/router/app_navigator.dart';
import 'package:recording_tool/core/utils/util_search_nasIp.dart';
import 'package:recording_tool/features/events/model/model_event_info.dart';
@@ -54,6 +53,14 @@ class _EventInfoPageState extends ConsumerState<EventInfoPage> {
time: item.scheduleTime,
playerName: item.playerName,
playerPhone: item.playerPhone,
isTeam: item.opponentId != '0',
opponentName: item.opponentName,
teamLeaderName: item.teamMembers.isNotEmpty
? item.teamMembers
.firstWhere((member) => member.isLeader)
.name
.trim()
: '',
),
streamUrl: streamUrl,
),
@@ -483,9 +490,10 @@ String _formatTitle(EventRegistrationItem item) {
}
String _formatVenue(EventRegistrationItem item, int scheduleIndex) {
final place = item.matchPlace.trim();
if (place.isEmpty) return '$scheduleIndex号场馆$scheduleIndex区';
return '$place号场馆$scheduleIndex区';
return item.matchPlace.trim();
// final place = item.matchPlace.trim();
// if (place.isEmpty) return '$scheduleIndex号场馆$scheduleIndex区';
// return '$place号场馆$scheduleIndex区';
}
String _formatScheduleTime(EventRegistrationItem item) {
@@ -518,9 +526,10 @@ String _formatOpponentLine(EventRegistrationItem item) {
}
String _formatNumberBadge(EventRegistrationItem item) {
final place = item.matchPlace.trim();
if (place.isEmpty) return '';
final match = RegExp(r'\d+').firstMatch(place);
if (match != null) return '${match.group(0)}';
return place;
return item.playerNo.trim().isEmpty ? '' : '${item.playerNo.trim()}';
// final place = item.matchPlace.trim();
// if (place.isEmpty) return '';
// final match = RegExp(r'\d+').firstMatch(place);
// if (match != null) return '${match.group(0)}号';
// return place;
}
@@ -9,6 +9,11 @@ class RecordingContext {
required this.playerPhone,
this.laneNo,
this.status,
this.isTeam = false,
/// 对方队长
this.opponentName = '',
this.teamLeaderName = '',
});
const RecordingContext.empty()
@@ -20,7 +25,10 @@ class RecordingContext {
playerName = '',
playerPhone = '',
laneNo = null,
status = null;
status = null,
isTeam = false,
opponentName = '',
teamLeaderName = '';
final String eventTitle;
final String matchName;
@@ -31,8 +39,12 @@ class RecordingContext {
final String playerPhone;
final String? laneNo;
final String? status;
final bool isTeam;
final String opponentName;
final String teamLeaderName;
String get title => '$matchName $group';
String get title =>
isTeam ? '$teamLeaderName 队伍 vs $opponentName 队伍' : '$playerName $group';
String get address => venue;
+143 -63
View File
@@ -9,9 +9,11 @@ import 'package:permission_handler/permission_handler.dart';
import 'package:recording_tool/app/router/app_navigator.dart';
import 'package:recording_tool/core/platform/app_platform_info.dart';
import 'package:recording_tool/core/platform/device_health_checker.dart';
import 'package:recording_tool/core/platform/device_health_snapshot.dart';
import 'package:recording_tool/features/recording/dialog/dialog-record.dart';
import 'package:recording_tool/features/recording/model/model_recording_context.dart';
import 'package:recording_tool/features/recording/platform/recording_platform.dart';
import 'package:recording_tool/features/recording/utils/recording_performance.dart';
import 'package:recording_tool/features/recording/view-model/view_model_recording.dart';
import 'package:recording_tool/features/recording/widgets/widget_camera_preview.dart';
import 'package:recording_tool/features/recording/widgets/widget_record_footer.dart';
@@ -21,6 +23,7 @@ import 'package:recording_tool/features/recording/widgets/widget_recording_hud.d
import 'package:recording_tool/features/recording/widgets/widget_recording_loading_overlay.dart';
import 'package:recording_tool/features/recording/widgets/widget_recording_saved_dialog.dart';
import 'package:recording_tool/features/recording/widgets/widget_recording_touch_lock_overlay.dart';
import 'package:recording_tool/features/scan_qrcode/pages/page_scan_qrcode.dart';
import 'package:recording_tool/features/scan_qrcode/utils/rtmp_stream_target.dart';
import 'package:recording_tool/shared/widgets/widgets.dart';
@@ -45,15 +48,23 @@ class _RecordingPageState extends ConsumerState<RecordingPage> {
var _immersiveApplied = false;
var _previewReady = false;
var _stoppingByUser = false;
var _bootstrapScheduled = false;
var _bootstrapStarted = false;
var _releasingResources = false;
var _controllerDisposed = false;
Animation<double>? _routeAnimation;
DeviceHealthSnapshot? _deviceHealthSnapshot;
Future<void>? _deviceHealthFuture;
final Stopwatch _pageEntryStopwatch = Stopwatch();
String? _mainCameraId;
String? _ultraWideCameraId;
double _ultraWideZoomRatio = 1.0;
@override
/// 首帧后初始化录制流程
/// 创建推流控制器,业务初始化等待路由动画结束。
void initState() {
super.initState();
_pageEntryStopwatch.start();
_streamController = ApiVideoLiveStreamController(
initialAudioConfig: AudioConfig(bitrate: 128000),
initialVideoConfig: VideoConfig.withDefaultBitrate(
@@ -88,20 +99,65 @@ class _RecordingPageState extends ConsumerState<RecordingPage> {
.setError(error.toString());
},
);
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
final animation = ModalRoute.of(context)?.animation;
if (identical(animation, _routeAnimation)) return;
_routeAnimation?.removeStatusListener(_handleRouteAnimationStatus);
_routeAnimation = animation;
if (animation == null || animation.status == AnimationStatus.completed) {
_scheduleBootstrap();
} else {
animation.addStatusListener(_handleRouteAnimationStatus);
}
}
void _handleRouteAnimationStatus(AnimationStatus status) {
if (status != AnimationStatus.completed) return;
logRecordingPerformance(
'route transition completed',
_pageEntryStopwatch.elapsed,
);
_scheduleBootstrap();
}
void _scheduleBootstrap() {
if (_bootstrapScheduled || _bootstrapStarted || _releasingResources) return;
_bootstrapScheduled = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || _releasingResources || _bootstrapStarted) return;
_bootstrapStarted = true;
_bootstrapScheduled = false;
_routeAnimation?.removeStatusListener(_handleRouteAnimationStatus);
_routeAnimation = null;
ref
.read(recordingViewModelProvider.notifier)
.setRecordingContext(widget.recordingContext);
_bootstrap();
unawaited(_bootstrap());
});
}
/// 检查设备健康状态并弹窗提示
Future<void> _checkAndShowDeviceHealthAlerts() async {
final snapshot = await AppPlatformInfo.deviceHealth();
if (!mounted) return;
Future<void> _loadDeviceHealth() async {
try {
_deviceHealthSnapshot = await measureRecordingOperation(
'device health',
AppPlatformInfo.deviceHealth,
);
} catch (error) {
debugPrint('读取设备健康状态失败: $error');
}
}
/// 使用当前页面缓存的健康状态,在开始录制前按需提示。
Future<void> _checkAndShowDeviceHealthAlerts() async {
_deviceHealthFuture ??= _loadDeviceHealth();
await _deviceHealthFuture;
if (!mounted) return;
final snapshot = _deviceHealthSnapshot;
if (snapshot == null) return;
final lines = DeviceHealthChecker.warningLines(snapshot);
if (lines.isEmpty) return;
@@ -112,16 +168,40 @@ class _RecordingPageState extends ConsumerState<RecordingPage> {
);
}
/// 页面启动:健康检查、进入录制模式、准备相机会话
/// 路由动画完成后再准备权限和相机,避免阻塞转场。
Future<void> _bootstrap() async {
await _checkAndShowDeviceHealthAlerts();
await measureRecordingOperation(
'enter immersive mode',
_enterRecordingMode,
);
if (!mounted) return;
final permissions = await ref
.read(recordingViewModelProvider.notifier)
.prepareRequiredPermissions();
if (!mounted) return;
if (!permissions.allGranted) return;
await measureRecordingOperation(
'preview initialize',
_initializeLiveStreamPreview,
);
if (!mounted || !_previewReady) return;
_deviceHealthFuture ??= _loadDeviceHealth();
unawaited(_loadPostPreviewTasks());
}
await _enterRecordingMode();
if (!mounted) return;
await ref.read(recordingViewModelProvider.notifier).prepareSession();
if (!mounted) return;
await _initializeLiveStreamPreview();
Future<void> _loadPostPreviewTasks() async {
try {
await Future.wait([
measureRecordingOperation(
'camera capabilities',
_loadBackCameraCapabilities,
),
ref.read(recordingViewModelProvider.notifier).loadSystemAdvisories(),
_deviceHealthFuture ??= _loadDeviceHealth(),
]);
} catch (error) {
debugPrint('加载录制页辅助状态失败: $error');
}
}
Future<void> _initializeLiveStreamPreview() async {
@@ -132,7 +212,6 @@ class _RecordingPageState extends ConsumerState<RecordingPage> {
ref
.read(recordingViewModelProvider.notifier)
.setPreviewReady(ready: true);
await _loadBackCameraCapabilities();
} on PlatformException catch (error) {
if (!mounted) return;
ref
@@ -154,6 +233,7 @@ class _RecordingPageState extends ConsumerState<RecordingPage> {
Future<void> _loadBackCameraCapabilities() async {
try {
final cameras = await _streamController.getBackCameras();
if (!mounted || _releasingResources) return;
if (cameras.isEmpty) return;
final main = cameras.first;
final widest = cameras.reduce(
@@ -179,6 +259,7 @@ class _RecordingPageState extends ConsumerState<RecordingPage> {
maxZoomRatio: 1.0,
);
} catch (_) {
if (!mounted || _releasingResources) return;
ref
.read(recordingViewModelProvider.notifier)
.updateZoomCapabilities(
@@ -217,8 +298,17 @@ class _RecordingPageState extends ConsumerState<RecordingPage> {
final ready = ref.read(recordingViewModelProvider).session.isPreviewReady;
if (ready) return true;
if (!mounted) return false;
AppToast.show('相机预览启动失败,请重试');
return false;
await measureRecordingOperation(
'preview initialize after permission',
_initializeLiveStreamPreview,
);
if (!mounted || !_previewReady) {
AppToast.show('相机预览启动失败,请重试');
return false;
}
_deviceHealthFuture ??= _loadDeviceHealth();
unawaited(_loadPostPreviewTasks());
return true;
}
if (!mounted) return false;
@@ -314,7 +404,7 @@ class _RecordingPageState extends ConsumerState<RecordingPage> {
/// 返回扫码页,准备新一轮录制。
void _recordNewRound() {
AppNavigator.pop(context: context);
AppNavigator.pushAndRemoveUntil(const ScanQrCodePage());
}
/// 推流结束后按需弹出完成对话框
@@ -337,50 +427,49 @@ class _RecordingPageState extends ConsumerState<RecordingPage> {
);
}
/// 退出沉浸式并释放录制会话。
/// 先恢复系统栏,再错开一帧释放编码器,减轻返回动画卡顿。
Future<void> _exitRecordingMode() async {
await _restoreSystemUiIfNeeded();
if (mounted) {
await ref.read(recordingViewModelProvider.notifier).teardown();
}
// 让 pop 动画先跑起来,再做 MediaCodec 释放。
await Future<void>.delayed(Duration.zero);
await _disposeStreamController();
}
Future<void> _restoreSystemUiIfNeeded() async {
if (!_immersiveApplied) return;
_immersiveApplied = false;
await SystemChrome.setEnabledSystemUIMode(
SystemUiMode.manual,
overlays: SystemUiOverlay.values,
);
await RecordingPlatform.setImmersiveMode(enabled: false);
}
@override
/// 页面销毁时兜底恢复系统 UI 并释放推流控制器
/// 路由反向动画结束、页面销毁后统一释放资源。
void dispose() {
if (_immersiveApplied) {
_immersiveApplied = false;
SystemChrome.setEnabledSystemUIMode(
SystemUiMode.manual,
overlays: SystemUiOverlay.values,
);
unawaited(RecordingPlatform.setImmersiveMode(enabled: false));
}
unawaited(_disposeStreamController());
_releasingResources = true;
_routeAnimation?.removeStatusListener(_handleRouteAnimationStatus);
_routeAnimation = null;
final viewModel = ref.read(recordingViewModelProvider.notifier);
unawaited(_releaseResources(viewModel));
super.dispose();
}
/// 只 dispose 一次;原生 dispose 内部已 stopStream,避免 stop+dispose 双次停流。
Future<void> _releaseResources(RecordingViewModel viewModel) async {
await measureRecordingOperation('page resource release', () async {
if (_immersiveApplied) {
_immersiveApplied = false;
try {
await SystemChrome.setEnabledSystemUIMode(
SystemUiMode.manual,
overlays: SystemUiOverlay.values,
);
await RecordingPlatform.setImmersiveMode(enabled: false);
} catch (error) {
debugPrint('恢复系统栏失败: $error');
}
}
try {
await viewModel.teardown();
} catch (error) {
debugPrint('清理录制状态失败: $error');
}
await _disposeStreamController();
});
}
/// 只 dispose 一次;原生 dispose 统一停止推流和预览。
Future<void> _disposeStreamController() async {
if (_controllerDisposed) return;
_controllerDisposed = true;
try {
await _streamController.dispose();
await measureRecordingOperation(
'stream controller dispose',
_streamController.dispose,
);
} catch (error, stackTrace) {
debugPrint('释放推流控制器失败: $error\n$stackTrace');
}
@@ -390,7 +479,6 @@ class _RecordingPageState extends ConsumerState<RecordingPage> {
/// 构建录制页 UI
Widget build(BuildContext context) {
return _RecordingPopScope(
onExitRecordingMode: _exitRecordingMode,
child: Scaffold(
backgroundColor: Colors.black,
body: Column(
@@ -426,12 +514,8 @@ class _RecordingPageState extends ConsumerState<RecordingPage> {
}
class _RecordingPopScope extends ConsumerWidget {
const _RecordingPopScope({
required this.onExitRecordingMode,
required this.child,
});
const _RecordingPopScope({required this.child});
final Future<void> Function() onExitRecordingMode;
final Widget child;
@override
@@ -443,11 +527,7 @@ class _RecordingPopScope extends ConsumerWidget {
return PopScope(
canPop: !isRecording,
onPopInvokedWithResult: (didPop, result) {
if (didPop) {
// 不 await,避免把 MediaCodec 释放堵在 Pop 回调上。
unawaited(onExitRecordingMode());
return;
}
if (didPop) return;
if (isRecording) {
AppToast.show('录制中无法返回,请先停止录制');
}
@@ -0,0 +1,25 @@
import 'package:flutter/foundation.dart';
Future<T> measureRecordingOperation<T>(
String label,
Future<T> Function() operation,
) async {
if (kReleaseMode) {
return operation();
}
final stopwatch = Stopwatch()..start();
try {
return await operation();
} finally {
stopwatch.stop();
debugPrint(
'[RecordingPerformance] $label: ${stopwatch.elapsedMilliseconds}ms',
);
}
}
void logRecordingPerformance(String label, Duration elapsed) {
if (kReleaseMode) return;
debugPrint('[RecordingPerformance] $label: ${elapsed.inMilliseconds}ms');
}
@@ -8,6 +8,7 @@ import 'package:recording_tool/features/recording/model/model_recording.dart';
import 'package:recording_tool/features/recording/model/model_recording_context.dart';
import 'package:recording_tool/features/recording/model/model_recording_session.dart';
import 'package:recording_tool/features/recording/platform/recording_platform.dart';
import 'package:recording_tool/features/recording/utils/recording_performance.dart';
/// 录制页状态 Provider。
final recordingViewModelProvider =
@@ -32,6 +33,8 @@ class RecordingRequiredPermissions {
class RecordingViewModel extends Notifier<RecordingModel> {
Timer? _elapsedTimer;
DateTime? _recordingStartedAt;
RecordingRequiredPermissions? _cachedRequiredPermissions;
var _sessionGeneration = 0;
/// 初始化状态并注册销毁回调。
@override
@@ -52,55 +55,88 @@ class RecordingViewModel extends Notifier<RecordingModel> {
state = state.copyWith(recordingContext: recordingContext);
}
/// 申请权限并检查系统设置
Future<void> prepareSession() async {
/// 准备相机和麦克风权限;已授权时复用当前会话结果
Future<RecordingRequiredPermissions> prepareRequiredPermissions({
bool forceRefresh = false,
}) async {
final generation = _sessionGeneration;
if (!RecordingPlatform.isSupported) {
_updateSession((s) => s.copyWith(errorMessage: '当前设备不支持录制'));
return;
return const RecordingRequiredPermissions(
cameraGranted: false,
microphoneGranted: false,
);
}
final permissions = await PermissionService.requestMissing([
Permission.camera,
Permission.microphone,
if (Platform.isAndroid) Permission.notification,
]);
final cameraGranted = permissions[Permission.camera]?.isGranted ?? false;
if (!cameraGranted) {
_updateSession((s) => s.copyWith(errorMessage: '需要相机权限才能录制'));
return;
final cached = _cachedRequiredPermissions;
if (!forceRefresh && cached?.allGranted == true) {
return cached!;
}
final microphoneGranted =
permissions[Permission.microphone]?.isGranted ?? false;
final permissions = await measureRecordingOperation(
'required permissions',
() => PermissionService.requestMissing([
Permission.camera,
Permission.microphone,
]),
);
final result = RecordingRequiredPermissions(
cameraGranted: _isPermissionGranted(permissions[Permission.camera]),
microphoneGranted: _isPermissionGranted(
permissions[Permission.microphone],
),
);
if (generation != _sessionGeneration) return result;
_cachedRequiredPermissions = result;
final errorMessage = !result.cameraGranted
? '需要相机权限才能录制'
: (!result.microphoneGranted ? '需要录音权限才能录制' : null);
_updateSession(
(s) => s.copyWith(
isMicrophoneGranted: result.microphoneGranted,
errorMessage: errorMessage,
),
);
return result;
}
/// 加载不影响相机首帧的通知、勿扰和电池状态。
Future<void> loadSystemAdvisories() async {
final generation = _sessionGeneration;
final notificationFuture = Platform.isAndroid
? PermissionService.requestMissing([Permission.notification])
: Future.value(<Permission, PermissionStatus>{});
final results = await measureRecordingOperation(
'system advisories',
() => Future.wait<dynamic>([
notificationFuture,
RecordingPlatform.hasNotificationPolicyAccess(),
RecordingPlatform.isIgnoringBatteryOptimizations(),
]),
);
final notificationPermissions =
results[0] as Map<Permission, PermissionStatus>;
final notificationsGranted = Platform.isAndroid
? (permissions[Permission.notification]?.isGranted ?? false)
? _isPermissionGranted(notificationPermissions[Permission.notification])
: true;
final hasDnd = results[1] as bool;
final batteryIgnored = results[2] as bool;
if (generation != _sessionGeneration) return;
final warnings = <String>[];
if (Platform.isAndroid && !notificationsGranted) {
warnings.add('未授予通知权限,录制时可能看不到前台服务通知,系统更容易结束后台录制');
}
if (!microphoneGranted) {
warnings.add('未授予麦克风权限,当前将以静音模式录制');
}
final hasDnd = await RecordingPlatform.hasNotificationPolicyAccess();
final batteryIgnored =
await RecordingPlatform.isIgnoringBatteryOptimizations();
_updateSession(
(s) => s.copyWith(
hasDndAccess: hasDnd,
isBatteryOptimizedIgnored: batteryIgnored,
isMicrophoneGranted: microphoneGranted,
notificationsGranted: notificationsGranted,
permissionWarning: warnings.isEmpty ? null : warnings.join('\n'),
errorMessage: null,
clearPermissionWarning: warnings.isEmpty,
),
);
_updateSession((s) => s.copyWith(errorMessage: null));
}
void setPreviewReady({required bool ready, String? errorMessage}) {
@@ -112,27 +148,8 @@ class RecordingViewModel extends Notifier<RecordingModel> {
/// 检测并尝试申请相机、麦克风权限,同步更新 session 中的 isMicrophoneGranted。
Future<RecordingRequiredPermissions>
ensureCameraAndMicrophonePermissions() async {
final permissions = await PermissionService.requestMissing([
Permission.camera,
Permission.microphone,
]);
final cameraGranted = _isPermissionGranted(permissions[Permission.camera]);
final microphoneGranted = _isPermissionGranted(
permissions[Permission.microphone],
);
_updateSession((s) => s.copyWith(isMicrophoneGranted: microphoneGranted));
if (cameraGranted && !state.session.isPreviewReady) {
_updateSession((s) => s.copyWith(errorMessage: null));
_updateSession((s) => s.copyWith(isPreviewReady: true));
}
return RecordingRequiredPermissions(
cameraGranted: cameraGranted,
microphoneGranted: microphoneGranted,
);
final cached = _cachedRequiredPermissions;
return prepareRequiredPermissions(forceRefresh: cached?.allGranted != true);
}
bool _isPermissionGranted(PermissionStatus? status) {
@@ -282,11 +299,13 @@ class RecordingViewModel extends Notifier<RecordingModel> {
/// 退出录制页时释放勿扰和会话状态(沉浸式由页面统一恢复)。
Future<void> teardown() async {
await RecordingPlatform.disableDoNotDisturb();
_sessionGeneration++;
_cachedRequiredPermissions = null;
_recordingStartedAt = null;
_elapsedTimer?.cancel();
_elapsedTimer = null;
state = state.copyWith(session: const RecordingSessionState());
await RecordingPlatform.disableDoNotDisturb();
}
/// Provider 销毁时取消状态流订阅。
@@ -10,9 +10,9 @@ Future<void> showRecordingSavedDialog(
}) {
return RecordDialog.showDouble(
context,
title: '本轮比赛视频已提交 NAS 录制\n请选择后续录制信息',
leftText: '续本轮',
rightText: '制新轮',
title: '本轮比赛视频已保存\n请选择后续录制信息',
leftText: '当前选手',
rightText: '新选手',
onLeftPressed: onContinueRound,
onRightPressed: onRecordNewRound,
barrierDismissible: false,
@@ -1,131 +0,0 @@
import 'package:apivideo_live_stream/apivideo_live_stream.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:recording_tool/features/scan_qrcode/utils/rtmp_stream_target.dart';
import 'package:recording_tool/shared/widgets/app_bar.dart';
import 'package:recording_tool/shared/widgets/app_toast.dart';
class PushSteamTestWidget extends StatefulWidget {
const PushSteamTestWidget({
super.key,
this.rtmpUrl =
'rtmp://192.168.1.245:19090/蔡依婷vs夏志豪_空中格斗赛_高中组/蔡依婷vs夏志豪_空中格斗赛_高中组',
});
final String rtmpUrl;
@override
State<PushSteamTestWidget> createState() => _PushSteamTestWidgetState();
}
class _PushSteamTestWidgetState extends State<PushSteamTestWidget>
with WidgetsBindingObserver {
late final ApiVideoLiveStreamController _controller;
bool _ready = false;
bool _isStreaming = false;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_controller = ApiVideoLiveStreamController(
initialAudioConfig: AudioConfig(bitrate: 128000),
initialVideoConfig: VideoConfig.withDefaultBitrate(
resolution: Resolution.RESOLUTION_1080,
fps: 30,
),
onConnectionSuccess: () => {
debugPrint('推流成功'),
setState(() => _isStreaming = true),
},
onConnectionFailed: (reason) {
setState(() => _isStreaming = false);
debugPrint('推流失败: $reason');
},
onDisconnection: () => {
debugPrint('推流断开'),
setState(() => _isStreaming = false),
},
);
WidgetsBinding.instance.addPostFrameCallback((_) => _initialize());
}
Future<void> _initialize() async {
try {
await _controller.initialize();
await _controller.startPreview();
setState(() => _ready = true);
} catch (e) {
debugPrint('初始化失败: $e');
}
}
Future<void> _startPush() async {
try {
final target = RtmpStreamTarget.parse(widget.rtmpUrl);
await _controller.startStreaming(
streamKey: target.streamKey,
url: target.url,
);
} on FormatException catch (e) {
debugPrint('推流地址错误: ${e.message}');
AppToast.show(e.message);
} on PlatformException catch (e) {
final message = e.message ?? e.code;
debugPrint('推流失败: ${e.code} $message');
AppToast.show('推流失败: $message');
} catch (e) {
debugPrint('推流失败: $e');
AppToast.showError(e);
}
}
Future<void> _stopPush() => _controller.stopStreaming();
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.inactive) {
_controller.stop();
} else if (state == AppLifecycleState.resumed) {
_controller.startPreview();
}
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: myAppBar(context: context),
body: Stack(
children: [
if (_ready)
ApiVideoCameraPreview(controller: _controller, fit: BoxFit.cover),
Positioned(
bottom: 32,
left: 0,
right: 0,
child: Center(
child: FloatingActionButton(
backgroundColor: _isStreaming ? Colors.red : Colors.green,
onPressed: _ready
? (_isStreaming ? _stopPush : _startPush)
: null,
child: Icon(_isStreaming ? Icons.stop : Icons.circle),
),
),
),
],
),
);
}
}
@@ -0,0 +1,395 @@
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get_thumbnail_video/index.dart';
import 'package:get_thumbnail_video/video_thumbnail.dart';
import 'package:recording_tool/app/router/app_navigator.dart';
import 'package:recording_tool/features/auth/model/model_auth.dart';
import 'package:recording_tool/features/auth/view_model_auth/view_model_auth.dart';
import 'package:recording_tool/features/scan_qrcode/pages/page_record_video_player.dart';
import 'package:recording_tool/gen/assets.gen.dart';
import 'package:recording_tool/shared/widgets/app_bar.dart';
import 'package:recording_tool/shared/widgets/app_empty_view.dart';
import 'package:recording_tool/shared/widgets/app_toast.dart';
/// NAS 文件服务地址,与 AuthServer.getRecordList 保持一致。
const _nasBaseUrl = 'http://sheling.local:9001';
const _videoExtensions = {
'mp4',
'mov',
'm4v',
'avi',
'mkv',
'flv',
'ts',
'wmv',
'webm',
'3gp',
};
/// 录像文件浏览页:目录逐级下钻,视频点击全屏播放。
class RecordListPage extends ConsumerWidget {
const RecordListPage({
super.key,
required this.breadcrumbs,
required this.items,
});
/// 面包屑,根页为 [赛事名],下钻时追加目录名。
final List<String> breadcrumbs;
final List<RecordListItem> items;
@override
Widget build(BuildContext context, WidgetRef ref) {
final visibleItems = items
.where((item) => _isDirectory(item) || _isVideoFile(item))
.toList(growable: false);
return Scaffold(
backgroundColor: const Color(0xFFF5F6F8),
appBar: AppPageBar(
centerTitle: false,
titleSpacing: 0,
titleWidget: Text(
breadcrumbs.join(' > '),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: Colors.white,
fontSize: 15.sp,
fontWeight: FontWeight.w500,
),
),
),
body: SafeArea(
top: false,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(height: 4.h),
Expanded(
child: visibleItems.isEmpty
? const AppEmptyView(message: '暂无录像内容')
: ListView.separated(
padding: EdgeInsets.fromLTRB(10.w, 8.h, 10.w, 24.h),
itemCount: visibleItems.length,
separatorBuilder: (_, _) => SizedBox(height: 8.h),
itemBuilder: (context, index) {
final item = visibleItems[index];
if (_isDirectory(item)) {
return _DirectoryCard(
item: item,
onTap: () => _openDirectory(context, ref, item),
);
}
return _VideoCard(
item: item,
onTap: () => _openVideo(context, item),
);
},
),
),
],
),
),
);
}
Future<void> _openDirectory(
BuildContext context,
WidgetRef ref,
RecordListItem item,
) async {
final path = item.path?.trim() ?? '';
if (path.isEmpty) {
AppToast.show('目录路径无效');
return;
}
EasyLoading.show(status: '加载中...');
try {
final children = await ref
.read(authProvider.notifier)
.fetchRecordList(path);
EasyLoading.dismiss();
if (children == null) {
AppToast.show('目录加载失败,请重试');
return;
}
if (!context.mounted) return;
final nextBreadcrumbs = [...breadcrumbs, item.name ?? ''];
AppNavigator.push(
RecordListPage(breadcrumbs: nextBreadcrumbs, items: children),
context: context,
// 多级目录复用同一页面类型,用路径区分路由,避免防重复拦截。
name: 'RecordListPage-$path',
);
} catch (error) {
EasyLoading.dismiss();
AppToast.show('目录加载失败,请重试');
}
}
void _openVideo(BuildContext context, RecordListItem item) {
final url = resolveRecordUrl(item.url?.trim() ?? '');
if (url.isEmpty) {
AppToast.show('视频地址无效');
return;
}
AppNavigator.push(
RecordVideoPlayerPage(url: url, title: item.name ?? ''),
context: context,
name: 'RecordVideoPlayerPage-$url',
);
}
}
bool _isDirectory(RecordListItem item) {
return item.type == RecordItemType.directory.value;
}
bool _isVideoFile(RecordListItem item) {
if (item.type != RecordItemType.file.value) return false;
var ext = (item.extension ?? '').toLowerCase();
if (ext.startsWith('.')) ext = ext.substring(1);
if (ext.isEmpty) {
final name = item.name ?? '';
final dotIndex = name.lastIndexOf('.');
if (dotIndex >= 0 && dotIndex < name.length - 1) {
ext = name.substring(dotIndex + 1).toLowerCase();
}
}
return _videoExtensions.contains(ext);
}
/// 相对地址补全 NAS 前缀。
String resolveRecordUrl(String raw) {
if (raw.isEmpty) return '';
if (raw.startsWith('http://') || raw.startsWith('https://')) return raw;
return raw.startsWith('/') ? '$_nasBaseUrl$raw' : '$_nasBaseUrl/$raw';
}
String _formatDate(DateTime? time) {
if (time == null) return '';
return '${time.year}-${time.month}-${time.day}';
}
class _DirectoryCard extends StatelessWidget {
const _DirectoryCard({required this.item, required this.onTap});
final RecordListItem item;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
final date = _formatDate(item.modTime);
return Material(
color: Colors.white,
borderRadius: BorderRadius.circular(6.r),
child: InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(6.r),
child: Container(
constraints: BoxConstraints(minHeight: 72.h),
padding: EdgeInsets.fromLTRB(20.w, 12.h, 14.w, 12.h),
child: Row(
children: [
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
item.name ?? '',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 14.sp,
height: 1.2,
color: const Color(0xFF30343A),
fontWeight: FontWeight.w600,
),
),
if (date.isNotEmpty) ...[
SizedBox(height: 6.h),
Text(
date,
style: TextStyle(
fontSize: 11.sp,
height: 1.2,
color: const Color(0xFF6E747D),
),
),
],
],
),
),
SizedBox(width: 12.w),
Row(
children: [
// Text(
// '视频',
// style: TextStyle(
// fontSize: 14.sp,
// color: const Color(0xFF358BFE),
// fontWeight: FontWeight.w600,
// ),
// ),
Icon(
Icons.chevron_right,
size: 20.r,
color: const Color(0xFF9AA3AF),
),
],
),
],
),
),
),
);
}
}
class _VideoCard extends StatelessWidget {
const _VideoCard({required this.item, required this.onTap});
final RecordListItem item;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
final date = _formatDate(item.modTime);
return Material(
color: Colors.white,
borderRadius: BorderRadius.circular(6.r),
child: InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(6.r),
child: Padding(
padding: EdgeInsets.all(10.r),
child: Row(
children: [
_VideoThumbnail(url: resolveRecordUrl(item.url?.trim() ?? '')),
SizedBox(width: 12.w),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
item.name ?? '',
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 14.sp,
height: 1.25,
color: const Color(0xFF30343A),
fontWeight: FontWeight.w600,
),
),
if (date.isNotEmpty) ...[
SizedBox(height: 6.h),
Text(
date,
style: TextStyle(
fontSize: 11.sp,
height: 1.2,
color: const Color(0xFF6E747D),
),
),
],
],
),
),
],
),
),
),
);
}
}
/// 视频首帧封面:异步生成缩略图,失败保留灰色占位,中央始终叠加播放图标。
class _VideoThumbnail extends StatefulWidget {
const _VideoThumbnail({required this.url});
final String url;
@override
State<_VideoThumbnail> createState() => _VideoThumbnailState();
}
class _VideoThumbnailState extends State<_VideoThumbnail> {
/// 按 url 缓存首帧,避免列表滚动重建时重复生成。
static final Map<String, Uint8List> _cache = {};
Uint8List? _bytes;
@override
void initState() {
super.initState();
_load();
}
Future<void> _load() async {
if (widget.url.isEmpty) return;
final cached = _cache[widget.url];
if (cached != null) {
_bytes = cached;
return;
}
try {
final data = await VideoThumbnail.thumbnailData(
video: widget.url,
imageFormat: ImageFormat.JPEG,
maxWidth: 320,
quality: 60,
);
_cache[widget.url] = data;
if (!mounted) return;
setState(() => _bytes = data);
} catch (_) {
// 生成失败保持占位图,不影响点击播放。
}
}
@override
Widget build(BuildContext context) {
return ClipRRect(
borderRadius: BorderRadius.circular(4.r),
child: SizedBox(
width: 108.w,
height: 68.h,
child: Stack(
fit: StackFit.expand,
children: [
ColoredBox(color: const Color(0xFFEDEFF2)),
if (_bytes != null)
Image.memory(_bytes!, fit: BoxFit.cover, gaplessPlayback: true),
Center(
child: Container(
width: 30.r,
height: 30.r,
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.35),
shape: BoxShape.circle,
),
child: Image(
image: AssetImage(Assets.images.imageVideoIcon.path),
fit: BoxFit.cover,
),
),
),
],
),
),
);
}
}
@@ -0,0 +1,250 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:recording_tool/app/router/app_navigator.dart';
import 'package:video_player/video_player.dart';
/// 录像全屏播放页:黑色背景,支持播放/暂停、进度拖动。
class RecordVideoPlayerPage extends StatefulWidget {
const RecordVideoPlayerPage({
super.key,
required this.url,
required this.title,
});
final String url;
final String title;
@override
State<RecordVideoPlayerPage> createState() => _RecordVideoPlayerPageState();
}
class _RecordVideoPlayerPageState extends State<RecordVideoPlayerPage> {
VideoPlayerController? _controller;
bool _initialized = false;
bool _hasError = false;
bool _showControls = true;
@override
void initState() {
super.initState();
_initController();
}
Future<void> _initController() async {
setState(() {
_hasError = false;
_initialized = false;
});
final old = _controller;
_controller = null;
await old?.dispose();
final controller = VideoPlayerController.networkUrl(Uri.parse(widget.url));
_controller = controller;
try {
await controller.initialize();
if (!mounted) return;
setState(() => _initialized = true);
await controller.play();
} catch (_) {
if (!mounted) return;
setState(() => _hasError = true);
}
}
@override
void dispose() {
_controller?.dispose();
super.dispose();
}
void _togglePlay() {
final controller = _controller;
if (controller == null || !_initialized) return;
setState(() {
if (controller.value.isPlaying) {
controller.pause();
} else {
controller.play();
}
});
}
@override
Widget build(BuildContext context) {
return AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle.light.copyWith(
statusBarColor: Colors.transparent,
systemNavigationBarColor: Colors.black,
),
child: Scaffold(
backgroundColor: Colors.black,
body: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () => setState(() => _showControls = !_showControls),
child: Stack(
fit: StackFit.expand,
children: [
Center(child: _buildPlayer()),
if (_showControls) _buildTopBar(),
if (_showControls && _initialized) _buildBottomControls(),
],
),
),
),
);
}
Widget _buildPlayer() {
if (_hasError) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
'视频加载失败',
style: TextStyle(color: Colors.white70, fontSize: 15.sp),
),
SizedBox(height: 14.h),
OutlinedButton(
onPressed: _initController,
style: OutlinedButton.styleFrom(
foregroundColor: Colors.white,
side: const BorderSide(color: Colors.white54),
),
child: const Text('重试'),
),
],
);
}
final controller = _controller;
if (controller == null || !_initialized) {
return const CircularProgressIndicator(color: Colors.white);
}
return AspectRatio(
aspectRatio: controller.value.aspectRatio,
child: VideoPlayer(controller),
);
}
Widget _buildTopBar() {
return Positioned(
top: 0,
left: 0,
right: 0,
child: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Colors.black54, Colors.transparent],
),
),
child: SafeArea(
bottom: false,
child: Row(
children: [
IconButton(
onPressed: () => AppNavigator.pop(context: context),
icon: Icon(
Icons.chevron_left_rounded,
color: Colors.white,
size: 30.r,
),
),
Expanded(
child: Text(
widget.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: Colors.white,
fontSize: 15.sp,
fontWeight: FontWeight.w500,
),
),
),
SizedBox(width: 48.w),
],
),
),
),
);
}
Widget _buildBottomControls() {
final controller = _controller!;
return Positioned(
left: 0,
right: 0,
bottom: 0,
child: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.bottomCenter,
end: Alignment.topCenter,
colors: [Colors.black54, Colors.transparent],
),
),
child: SafeArea(
top: false,
child: Padding(
padding: EdgeInsets.fromLTRB(12.w, 8.h, 12.w, 8.h),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
VideoProgressIndicator(
controller,
allowScrubbing: true,
colors: const VideoProgressColors(
playedColor: Colors.white,
bufferedColor: Colors.white38,
backgroundColor: Colors.white24,
),
padding: EdgeInsets.symmetric(vertical: 8.h),
),
ValueListenableBuilder<VideoPlayerValue>(
valueListenable: controller,
builder: (context, value, _) {
return Row(
children: [
IconButton(
onPressed: _togglePlay,
icon: Icon(
value.isPlaying
? Icons.pause_rounded
: Icons.play_arrow_rounded,
color: Colors.white,
size: 30.r,
),
),
Text(
'${_formatDuration(value.position)} / ${_formatDuration(value.duration)}',
style: TextStyle(
color: Colors.white,
fontSize: 12.sp,
),
),
],
);
},
),
],
),
),
),
),
);
}
}
String _formatDuration(Duration duration) {
final minutes = duration.inMinutes.toString().padLeft(2, '0');
final seconds = (duration.inSeconds % 60).toString().padLeft(2, '0');
final hours = duration.inHours;
if (hours > 0) return '$hours:$minutes:$seconds';
return '$minutes:$seconds';
}
@@ -7,30 +7,16 @@ import 'package:recording_tool/app/router/app_navigator.dart';
import 'package:recording_tool/core/cache/app_storage.dart';
import 'package:recording_tool/core/cache/storage_keys.dart';
import 'package:recording_tool/features/auth/view_model_auth/view_model_auth.dart';
import 'package:recording_tool/features/competition_teams/pages/page_competition_team_list.dart';
import 'package:recording_tool/features/events/model/model_event_info.dart';
import 'package:recording_tool/features/events/pages/page_event_info.dart';
import 'package:recording_tool/features/events/view_model/view_model_event_info.dart';
import 'package:recording_tool/features/recording/model/model_recording_context.dart';
import 'package:recording_tool/features/scan_qrcode/pages/page_record_list.dart';
import 'package:recording_tool/shared/widgets/app_qr_scanner_dialog.dart';
import 'package:recording_tool/shared/widgets/app_toast.dart';
class ScanQrCodePage extends ConsumerStatefulWidget {
const ScanQrCodePage({super.key});
static const mockRtmpUrl =
'rtmp://192.168.1.245:19090/蔡依婷vs夏志豪_空中格斗赛_高中组/蔡依婷vs夏志豪_空中格斗赛_高中组';
static const mockRecordingContext = RecordingContext(
eventTitle: '全国青少年无人机大赛',
matchName: '空中格斗赛',
group: '高中组',
venue: '场地 1',
time: '7月1日 12:00-15:00',
playerName: '蔡依婷vs夏志豪',
playerPhone: '',
);
@override
ConsumerState<ScanQrCodePage> createState() => _ScanQrCodePageState();
}
@@ -140,18 +126,18 @@ class _ScanQrCodePageState extends ConsumerState<ScanQrCodePage> {
onPressed: _handleViewRecords,
),
),
SizedBox(width: 12.w),
Expanded(
child: _BottomOutlineButton(
label: '参赛队伍',
onPressed: () async {
await AppNavigator.push(
const CompetitionTeamListPage(),
context: context,
);
},
),
),
// SizedBox(width: 12.w),
// Expanded(
// child: _BottomOutlineButton(
// label: '参赛队伍',
// onPressed: () async {
// await AppNavigator.push(
// const CompetitionTeamListPage(),
// context: context,
// );
// },
// ),
// ),
],
),
],
@@ -209,7 +195,13 @@ class _ScanQrCodePageState extends ConsumerState<ScanQrCodePage> {
AppToast.show('暂无录像');
return;
}
AppToast.show('录像列表已更新');
if (!mounted) return;
final items = ref.read(authProvider).recordList ?? const [];
AppNavigator.push(
RecordListPage(breadcrumbs: [eventName.trim()], items: items),
context: context,
);
} catch (error) {
EasyLoading.dismiss();
AppToast.show('查询录像失败');
@@ -225,18 +217,50 @@ class _BrandHeader extends StatelessWidget {
return Row(
mainAxisSize: MainAxisSize.min,
children: [
Image.asset(
_ScanAssets.appIcon,
width: 34.w,
height: 34.w,
fit: BoxFit.cover,
Expanded(
child: Row(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(17.r),
child: Image.asset(
_ScanAssets.appIcon,
width: 34.w,
height: 34.w,
fit: BoxFit.cover,
),
),
// SizedBox(width: .w),
Image.asset(
_ScanAssets.appNameText,
width: 117.w,
height: 29.w,
fit: BoxFit.contain,
),
],
),
),
SizedBox(width: 8.w),
Image.asset(
_ScanAssets.appNameText,
width: 117.w,
height: 29.w,
fit: BoxFit.contain,
GestureDetector(
onTap: () {
AppNavigator.pop();
},
child: Row(
children: [
Icon(
Icons.chevron_left_rounded,
color: Colors.black,
size: 28.sp,
),
Text(
'返回',
style: TextStyle(
// color: const Color(0xFF53A7F3),
color: Colors.black,
fontSize: 14.sp,
fontWeight: FontWeight.w400,
),
),
],
),
),
],
);
+10
View File
@@ -76,6 +76,14 @@ class $AssetsImagesGen {
AssetGenImage get imageStart =>
const AssetGenImage('assets/images/image_start.png');
/// File path: assets/images/image_team_vs_bg.png
AssetGenImage get imageTeamVsBg =>
const AssetGenImage('assets/images/image_team_vs_bg.png');
/// File path: assets/images/image_video_icon.png
AssetGenImage get imageVideoIcon =>
const AssetGenImage('assets/images/image_video_icon.png');
/// File path: assets/images/image_vs.png
AssetGenImage get imageVs =>
const AssetGenImage('assets/images/image_vs.png');
@@ -95,6 +103,8 @@ class $AssetsImagesGen {
imageScan,
imageScanQrcode,
imageStart,
imageTeamVsBg,
imageVideoIcon,
imageVs,
];
}
+8 -1
View File
@@ -14,6 +14,8 @@ class AppPageBar extends StatelessWidget implements PreferredSizeWidget {
this.backgroundImage,
this.onBack,
this.actions,
this.centerTitle = true,
this.titleSpacing,
});
final String title;
@@ -22,6 +24,10 @@ class AppPageBar extends StatelessWidget implements PreferredSizeWidget {
final VoidCallback? onBack;
final List<Widget>? actions;
/// 标题是否居中;false 时左对齐,紧随返回按钮。
final bool centerTitle;
final double? titleSpacing;
@override
Size get preferredSize => const Size.fromHeight(kToolbarHeight);
@@ -33,7 +39,8 @@ class AppPageBar extends StatelessWidget implements PreferredSizeWidget {
backgroundColor: Colors.transparent,
elevation: 0,
scrolledUnderElevation: 0,
centerTitle: true,
centerTitle: centerTitle,
titleSpacing: titleSpacing,
systemOverlayStyle: SystemUiOverlayStyle.light,
flexibleSpace: SizedBox.expand(
child: Image.asset(
@@ -2,6 +2,8 @@ package video.api.flutter.livestream
import android.Manifest
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.util.Size
import android.view.Surface
import io.flutter.view.TextureRegistry
@@ -17,7 +19,15 @@ import io.github.thibaultbee.streampack.utils.frontCameraList
import io.github.thibaultbee.streampack.utils.isBackCamera
import io.github.thibaultbee.streampack.utils.isExternalCamera
import io.github.thibaultbee.streampack.utils.isFrontCamera
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
class FlutterLiveStreamView(
private val context: Context,
@@ -39,9 +49,21 @@ class FlutterLiveStreamView(
initialOnConnectionListener = this,
initialOnErrorListener = this
)
private val mainHandler = Handler(Looper.getMainLooper())
private val operationScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val operationMutex = Mutex()
private val disposeLock = Any()
private val disposeCallbacks =
mutableListOf<Pair<() -> Unit, (Exception) -> Unit>>()
@Volatile
private var _isPreviewing = false
@Volatile
private var _isStreaming = false
@Volatile
private var _isDisposing = false
@Volatile
private var _isDisposed = false
val isStreaming: Boolean
get() = _isStreaming
@@ -63,7 +85,7 @@ class FlutterLiveStreamView(
val wasPreviewing = _isPreviewing
if (wasPreviewing) {
stopPreview()
stopPreviewInternal()
}
streamer.configure(videoConfig)
_videoConfig = videoConfig
@@ -174,23 +196,58 @@ class FlutterLiveStreamView(
setCamera(cameraList.first(), onSuccess, onError)
}
fun dispose() {
try {
stopStream()
} catch (e: Exception) {
android.util.Log.w("ApiVideoLiveStream", "stopStream during dispose failed", e)
_isStreaming = false
fun dispose(onSuccess: () -> Unit, onError: (Exception) -> Unit) {
var shouldStartDispose = false
synchronized(disposeLock) {
if (_isDisposed) {
mainHandler.post(onSuccess)
return
}
disposeCallbacks.add(onSuccess to onError)
if (!_isDisposing) {
_isDisposing = true
shouldStartDispose = true
}
}
try {
streamer.stopPreview()
} catch (e: Exception) {
android.util.Log.w("ApiVideoLiveStream", "stopPreview during dispose failed", e)
if (!shouldStartDispose) return
operationScope.launch {
var failure: Exception? = null
operationMutex.withLock {
try {
stopStreamInternal()
} catch (e: Exception) {
android.util.Log.w("ApiVideoLiveStream", "stopStream during dispose failed", e)
failure = e
}
try {
stopPreviewInternal()
} catch (e: Exception) {
android.util.Log.w("ApiVideoLiveStream", "stopPreview during dispose failed", e)
failure = failure ?: e
}
}
withContext(Dispatchers.Main.immediate) {
try {
flutterTexture.release()
} catch (e: Exception) {
failure = failure ?: e
}
val callbacks = synchronized(disposeLock) {
_isDisposed = true
_isDisposing = false
disposeCallbacks.toList().also { disposeCallbacks.clear() }
}
callbacks.forEach { (success, error) ->
failure?.let(error) ?: success()
}
}
operationScope.cancel()
}
_isPreviewing = false
flutterTexture.release()
}
fun startStream(url: String) {
check(!_isDisposing && !_isDisposed) { "Live stream has been disposed" }
runBlocking {
streamer.connect(url)
try {
@@ -204,29 +261,31 @@ class FlutterLiveStreamView(
}
}
fun stopStream() {
if (!_isStreaming && !streamer.isConnected) {
return
fun stopStream(onSuccess: () -> Unit, onError: (Exception) -> Unit) {
runBackgroundOperation(onSuccess, onError) {
stopStreamInternal()
}
}
private suspend fun stopStreamInternal() {
if (!_isStreaming && !streamer.isConnected) return
val isConnected = streamer.isConnected
var failure: Exception? = null
try {
runBlocking {
streamer.stopStream()
streamer.disconnect()
if (isConnected) {
onDisconnected()
}
_isStreaming = false
}
streamer.stopStream()
} catch (e: Exception) {
android.util.Log.w("ApiVideoLiveStream", "stopStream failed", e)
_isStreaming = false
try {
streamer.disconnect()
} catch (_: Exception) {
// ignore secondary disconnect failures
}
failure = e
}
try {
streamer.disconnect()
} catch (e: Exception) {
failure = failure ?: e
}
if (isConnected) {
onDisconnected()
}
_isStreaming = false
failure?.let { throw it }
}
fun startPreview(onSuccess: () -> Unit, onError: (Exception) -> Unit) {
@@ -262,11 +321,40 @@ class FlutterLiveStreamView(
})
}
fun stopPreview() {
fun stopPreview(onSuccess: () -> Unit, onError: (Exception) -> Unit) {
runBackgroundOperation(onSuccess, onError) {
stopPreviewInternal()
}
}
private fun stopPreviewInternal() {
if (!_isPreviewing) return
streamer.stopPreview()
_isPreviewing = false
}
private fun runBackgroundOperation(
onSuccess: () -> Unit,
onError: (Exception) -> Unit,
operation: suspend () -> Unit,
) {
if (_isDisposing || _isDisposed) {
mainHandler.post(onSuccess)
return
}
operationScope.launch {
val failure = try {
operationMutex.withLock { operation() }
null
} catch (e: Exception) {
e
}
withContext(Dispatchers.Main.immediate) {
failure?.let(onError) ?: onSuccess()
}
}
}
private fun getSurface(resolution: Size): Surface {
val surfaceTexture = flutterTexture.surfaceTexture().apply {
setDefaultBufferSize(
@@ -50,27 +50,44 @@ class MethodCallHandlerImpl(
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
when (call.method) {
"create" -> {
try {
flutterView?.dispose()
flutterView = FlutterLiveStreamView(
context,
textureRegistry,
permissionsManager,
{ sendConnected() },
{ sendDisconnected() },
{ sendConnectionFailed(it) },
{ sendError(it) },
{ sendVideoSizeChanged(it) }
val previousView = flutterView
if (previousView == null) {
createFlutterView(result)
} else {
previousView.dispose(
onSuccess = {
if (flutterView === previousView) {
flutterView = null
}
createFlutterView(result)
},
onError = {
result.error("failed_to_replace_live_stream", it.message, null)
},
)
result.success(mapOf("textureId" to flutterView!!.textureId))
} catch (e: Exception) {
result.error("failed_to_create_live_stream", e.message, null)
}
}
"dispose" -> {
flutterView?.dispose()
flutterView = null
val view = flutterView
if (view == null) {
result.success(null)
} else {
view.dispose(
onSuccess = {
if (flutterView === view) {
flutterView = null
}
result.success(null)
},
onError = {
if (flutterView === view) {
flutterView = null
}
result.error("failed_to_dispose_live_stream", it.message, null)
},
)
}
}
"setVideoConfig" -> {
@@ -128,8 +145,17 @@ class MethodCallHandlerImpl(
}
"stopPreview" -> {
flutterView?.stopPreview()
result.success(null)
val view = flutterView
if (view == null) {
result.success(null)
} else {
view.stopPreview(
onSuccess = { result.success(null) },
onError = {
result.error("failed_to_stop_preview", it.message, null)
},
)
}
}
"startStreaming" -> {
@@ -163,8 +189,17 @@ class MethodCallHandlerImpl(
}
"stopStreaming" -> {
flutterView?.stopStream()
result.success(null)
val view = flutterView
if (view == null) {
result.success(null)
} else {
view.stopStream(
onSuccess = { result.success(null) },
onError = {
result.error("failed_to_stop_stream", it.message, null)
},
)
}
}
"getIsStreaming" -> result.success(mapOf("isStreaming" to flutterView!!.isStreaming))
@@ -275,6 +310,24 @@ class MethodCallHandlerImpl(
}
}
private fun createFlutterView(result: MethodChannel.Result) {
try {
flutterView = FlutterLiveStreamView(
context,
textureRegistry,
permissionsManager,
{ sendConnected() },
{ sendDisconnected() },
{ sendConnectionFailed(it) },
{ sendError(it) },
{ sendVideoSizeChanged(it) },
)
result.success(mapOf("textureId" to flutterView!!.textureId))
} catch (e: Exception) {
result.error("failed_to_create_live_stream", e.message, null)
}
}
private fun sendConnected() {
sendEvent("connected")
}
@@ -68,7 +68,6 @@ class _ApiVideoCameraPreviewState extends State<ApiVideoCameraPreview> {
@override
void dispose() {
widget.controller.stopPreview();
widget.controller.removeWidgetListener(_widgetListener);
widget.controller.removeEventsListener(_eventsListener);
super.dispose();
@@ -26,6 +26,8 @@ class ApiVideoLiveStreamController {
int get textureId => _textureId;
bool _isInitialized = false;
Future<void>? _initializeFuture;
Future<void>? _disposeFuture;
/// Gets the current state of the video player.
bool get isInitialized => _isInitialized;
@@ -68,7 +70,14 @@ class ApiVideoLiveStreamController {
}
/// Creates a new live stream instance with initial audio and video configurations.
Future<void> initialize() async {
Future<void> initialize() {
if (_disposeFuture != null) {
throw StateError('Cannot initialize a disposed controller');
}
return _initializeFuture ??= _initialize();
}
Future<void> _initialize() async {
_textureId = await _platform.initialize() ?? kUninitializedTextureId;
_eventSubscription = _platform
@@ -91,12 +100,23 @@ class ApiVideoLiveStreamController {
}
/// Disposes the live stream instance.
Future<void> dispose() async {
Future<void> dispose() {
return _disposeFuture ??= _dispose();
}
Future<void> _dispose() async {
try {
await _initializeFuture;
} catch (_) {
// A partially initialized native view still needs to be disposed.
}
await _eventSubscription?.cancel();
_eventSubscription = null;
_eventsListeners.clear();
_widgetListeners.clear();
await _platform.dispose();
return;
_isInitialized = false;
_textureId = kUninitializedTextureId;
}
/// Sets new video parameters.
+2
View File
@@ -55,6 +55,8 @@ dependencies:
path: plugins/apivideo_live_stream
jwt_decoder: ^2.0.1
network_info_plus: ^7.0.0
video_player: ^2.13.0
get_thumbnail_video: ^0.7.3
dev_dependencies:
flutter_test: