feat: 新增诊断报告全流程功能,适配登录后报告跳转逻辑
实现了入门测/出门测报告的完整链路: 1. 新增UserInfo模型的出门测报告标记字段与相关接口 2. 新增全局报告路由拦截器,自动在登录后/应用回前台时检查报告状态 3. 新增报告相关API、页面与路由配置,包含欢迎页、H5壳子、AI计算页 4. 适配登录成功后的报告跳转逻辑,更新用户状态管理方法
This commit is contained in:
@@ -0,0 +1,440 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:new_learn/core/api/auth/api.dart';
|
||||
import 'package:new_learn/core/api/report/api.dart';
|
||||
import 'package:new_learn/core/api/report/model.dart';
|
||||
import 'package:new_learn/core/logger/app_talker.dart';
|
||||
import 'package:new_learn/core/providers/user_provider.dart';
|
||||
|
||||
/// ============================================================
|
||||
/// 【ReportComputationPage】AI 加载动画页 —— 对标 Vue reportComputation.vue
|
||||
///
|
||||
/// 入门测 H5 壳子看完所有科目报告 → navigateTo reportComputation →
|
||||
/// 圆环进度 + 每个科目依次"AI计算中"动画 → finishedPopup 弹窗 →
|
||||
/// 调 ChangeShowReport → refresh userProvider → switchTab 首页
|
||||
/// ============================================================
|
||||
class ReportComputationPage extends ConsumerStatefulWidget {
|
||||
const ReportComputationPage({super.key});
|
||||
|
||||
@override
|
||||
ConsumerState<ReportComputationPage> createState() =>
|
||||
_ReportComputationPageState();
|
||||
}
|
||||
|
||||
class _ReportComputationPageState extends ConsumerState<ReportComputationPage> {
|
||||
List<_SubjectData> _subjectList = [];
|
||||
int _ringProgress = 0;
|
||||
bool _showFinishedPopup = false;
|
||||
int _currentIndex = -1;
|
||||
Timer? _animTimer;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) => _loadAndStart());
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_animTimer?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _loadAndStart() async {
|
||||
try {
|
||||
final results = await Future.wait([
|
||||
ReportApi.instance.getCurrentReport(),
|
||||
ReportApi.instance.getCurrentReportKnow(),
|
||||
]);
|
||||
final report = results[0] as UserReportType;
|
||||
final knowList = results[1] as List<UserReportKnowType>;
|
||||
|
||||
if (report.subjectReports.isEmpty) return;
|
||||
|
||||
final itemTime = (15 / report.subjectReports.length).floor();
|
||||
setState(() {
|
||||
_subjectList = report.subjectReports.map((item) {
|
||||
final knowItem = knowList.isNotEmpty
|
||||
? knowList.firstWhere(
|
||||
(k) => k.subjectName == item.subjectName,
|
||||
orElse: () => const UserReportKnowType(),
|
||||
)
|
||||
: const UserReportKnowType();
|
||||
return _SubjectData(
|
||||
subjectReport: item,
|
||||
knowCount: knowItem.knowCount,
|
||||
time: itemTime,
|
||||
);
|
||||
}).toList();
|
||||
});
|
||||
_startSubjects(0);
|
||||
} catch (e) {
|
||||
talker.error('reportComputation 加载失败', e);
|
||||
}
|
||||
}
|
||||
|
||||
void _startSubjects(int index) {
|
||||
if (index >= _subjectList.length) {
|
||||
setState(() {
|
||||
_ringProgress = 100;
|
||||
_showFinishedPopup = true;
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setState(() {
|
||||
_currentIndex = index;
|
||||
_subjectList[index].status = _SubjectStatus.inProgress;
|
||||
_subjectList[index].progress = 0;
|
||||
});
|
||||
|
||||
final totalTimeMs = _subjectList[index].time * 1000;
|
||||
final startTime = DateTime.now().millisecondsSinceEpoch;
|
||||
|
||||
_animTimer = Timer.periodic(const Duration(milliseconds: 30), (timer) {
|
||||
final elapsed = DateTime.now().millisecondsSinceEpoch - startTime;
|
||||
final progress = (elapsed / totalTimeMs * 100).clamp(0, 100).toInt();
|
||||
|
||||
setState(() {
|
||||
_subjectList[index].progress = progress;
|
||||
_ringProgress =
|
||||
((index * 100) + progress) ~/ _subjectList.length;
|
||||
});
|
||||
|
||||
if (elapsed >= totalTimeMs) {
|
||||
timer.cancel();
|
||||
_animTimer = null;
|
||||
setState(() {
|
||||
_subjectList[index].progress = 100;
|
||||
_subjectList[index].status = _SubjectStatus.finished;
|
||||
});
|
||||
_startSubjects(index + 1);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// finishedPopup 的"立即开启学习蝶变"按钮
|
||||
Future<void> _onFinish() async {
|
||||
try {
|
||||
await UserApi.changeShowReport();
|
||||
talker.debug('changeShowReport 成功');
|
||||
await ref.read(currentUserProvider.notifier).refresh();
|
||||
} catch (e) {
|
||||
talker.error('changeShowReport 失败', e);
|
||||
}
|
||||
if (!mounted) return;
|
||||
context.go('/');
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: const Color(0xFF0F1A2E),
|
||||
body: Stack(
|
||||
children: [
|
||||
SafeArea(
|
||||
child: Column(
|
||||
children: [
|
||||
const SizedBox(height: 16),
|
||||
const Text(
|
||||
'AI智能生成学习计划',
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 15,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
// 圆环进度
|
||||
_ProgressRing(progress: _ringProgress),
|
||||
const SizedBox(height: 20),
|
||||
// 科目列表
|
||||
Expanded(
|
||||
child: ListView.separated(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 14,
|
||||
vertical: 10,
|
||||
),
|
||||
itemCount: _subjectList.length,
|
||||
separatorBuilder: (_, __) => const SizedBox(height: 8),
|
||||
itemBuilder: (_, index) {
|
||||
return _SubjectItem(data: _subjectList[index]);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
// finishedPopup 弹窗
|
||||
if (_showFinishedPopup)
|
||||
Positioned.fill(
|
||||
child: Container(
|
||||
color: Colors.black54,
|
||||
child: Center(
|
||||
child: Container(
|
||||
width: 320,
|
||||
padding: const EdgeInsets.all(24),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Icon(Icons.check_circle,
|
||||
size: 48, color: Color(0xFF10C79C)),
|
||||
const SizedBox(height: 12),
|
||||
const Text(
|
||||
'报告生成完成',
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: Color(0xFF1D2B47),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
height: 50,
|
||||
child: ElevatedButton(
|
||||
onPressed: _onFinish,
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: const Color(0xFF3D7DF5),
|
||||
foregroundColor: Colors.white,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(25),
|
||||
),
|
||||
elevation: 0,
|
||||
),
|
||||
child: const Text('立即开启学习蝶变'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 内部数据类 ====================
|
||||
|
||||
enum _SubjectStatus { notStarted, inProgress, finished }
|
||||
|
||||
class _SubjectData {
|
||||
final SubjectReportType subjectReport;
|
||||
int progress;
|
||||
_SubjectStatus status;
|
||||
int time;
|
||||
int knowCount;
|
||||
|
||||
_SubjectData({
|
||||
required this.subjectReport,
|
||||
required this.time,
|
||||
required this.knowCount,
|
||||
this.progress = 0,
|
||||
this.status = _SubjectStatus.notStarted,
|
||||
});
|
||||
}
|
||||
|
||||
// ==================== 圆环进度组件 ====================
|
||||
|
||||
class _ProgressRing extends StatelessWidget {
|
||||
const _ProgressRing({required this.progress});
|
||||
final int progress;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SizedBox(
|
||||
width: 262,
|
||||
height: 262,
|
||||
child: Stack(
|
||||
alignment: Alignment.center,
|
||||
children: [
|
||||
// 背景圈
|
||||
SizedBox(
|
||||
width: 240,
|
||||
height: 240,
|
||||
child: CircularProgressIndicator(
|
||||
value: 1.0,
|
||||
strokeWidth: 8,
|
||||
backgroundColor: Colors.white.withValues(alpha: 0.1),
|
||||
valueColor: const AlwaysStoppedAnimation<Color>(
|
||||
Color(0xFF1D2B47),
|
||||
),
|
||||
),
|
||||
),
|
||||
// 进度圈
|
||||
SizedBox(
|
||||
width: 240,
|
||||
height: 240,
|
||||
child: CircularProgressIndicator(
|
||||
value: progress / 100,
|
||||
strokeWidth: 8,
|
||||
backgroundColor: Colors.transparent,
|
||||
valueColor: const AlwaysStoppedAnimation<Color>(
|
||||
Color(0xFF3D7DF5),
|
||||
),
|
||||
),
|
||||
),
|
||||
// 中心文字
|
||||
Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
'$progress%',
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 40,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
const Text(
|
||||
'AI加载中',
|
||||
style: TextStyle(
|
||||
color: Color(0xFF687FAD),
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 科目卡片组件 ====================
|
||||
|
||||
class _SubjectItem extends StatelessWidget {
|
||||
const _SubjectItem({required this.data});
|
||||
final _SubjectData data;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isFinished = data.status == _SubjectStatus.finished;
|
||||
final isInProgress = data.status == _SubjectStatus.inProgress;
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(14),
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
colors: isFinished
|
||||
? const [Color(0xFFE3FCF4), Color(0xFFF7FCFA), Colors.white]
|
||||
: const [Color(0xFFE3F7FC), Color(0xFFF7FBFC), Colors.white],
|
||||
),
|
||||
boxShadow: const [
|
||||
BoxShadow(
|
||||
color: Colors.black12,
|
||||
blurRadius: 6,
|
||||
offset: Offset(0, 2),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
// 状态徽章
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: isFinished
|
||||
? const Color(0xFF19CE92)
|
||||
: isInProgress
|
||||
? const Color(0xFF3D7DF5)
|
||||
: const Color(0xFFC0C4CC),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
child: Text(
|
||||
'${data.progress}%',
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
// 科目图标
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: data.subjectReport.icon.isNotEmpty
|
||||
? Image.network(
|
||||
data.subjectReport.icon,
|
||||
width: 26,
|
||||
height: 26,
|
||||
fit: BoxFit.cover,
|
||||
errorBuilder: (_, __, ___) => const Icon(
|
||||
Icons.menu_book,
|
||||
size: 26,
|
||||
color: Color(0xFF3D7DF5),
|
||||
),
|
||||
)
|
||||
: const Icon(
|
||||
Icons.menu_book,
|
||||
size: 26,
|
||||
color: Color(0xFF3D7DF5),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
data.subjectReport.subjectName,
|
||||
style: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: Color(0xFF1D2B47),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
// 科目内部进度条
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
child: LinearProgressIndicator(
|
||||
value: data.progress / 100,
|
||||
backgroundColor: const Color(0xFFE1EAFA),
|
||||
valueColor: AlwaysStoppedAnimation<Color>(
|
||||
isFinished
|
||||
? const Color(0xFF19CE92)
|
||||
: const Color(0xFF3D7DF5),
|
||||
),
|
||||
minHeight: 4,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
// 知识点数量
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 3),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFFE1EAFA),
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
child: Text(
|
||||
'${data.knowCount}',
|
||||
style: const TextStyle(
|
||||
fontSize: 12,
|
||||
color: Color(0xFF3D7DF5),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:new_learn/core/config/app_config.dart';
|
||||
import 'package:new_learn/core/logger/app_talker.dart';
|
||||
import 'package:new_learn/core/network/dio_client.dart';
|
||||
|
||||
/// ============================================================
|
||||
/// 【ReportWebViewPage】报告 H5 壳子容器 —— 对标 Vue reportWebView.vue
|
||||
///
|
||||
/// 承载已上线的 H5 壳子(App.K12.Student.Report),它内部自己加载
|
||||
/// 每个科目的报告 URL 并提供"跳过/下一步"按钮。
|
||||
///
|
||||
/// Flutter 端负责:
|
||||
/// 1. 拼 H5 壳子的加载 URL(baseURL / token / type / safeBottom);
|
||||
/// 2. 注入 window.uni JS Bridge(switchTab / navigateTo / reLaunch),
|
||||
/// 让 H5 壳子里已有的 `window.uni.switchTab(...)` 等调用自然生效。
|
||||
/// 【通信方式】:用 console.log('[FLUTTER_BRIDGE] xxx url') + onConsoleMessage 监听,
|
||||
/// 而不是 InAppWebView.callHandler/addJavaScriptHandler。
|
||||
/// 原因:callHandler 在真机上首次 onLoadStop 注入时偶尔能通,
|
||||
/// 但 H5 后续真实点击触发时就失效了(之前加的 _isExiting 锁导致死循环,
|
||||
/// 去掉锁也没收到调用);console.log 通道每次都能收到,更稳定。
|
||||
/// 3. H5 壳子自己调 updateAfterReportStatus() 更新出门测状态,
|
||||
/// Flutter Bridge 只负责路由跳转,职责单一不重复。
|
||||
///
|
||||
/// 路由参数(GoRouteState.extra):
|
||||
/// context.push('/reportWebView', extra: {'type': 'placementTest'});
|
||||
///
|
||||
/// H5 路径 → Flutter 路由映射表:见 _h5PathMap
|
||||
/// ============================================================
|
||||
class ReportWebViewPage extends ConsumerStatefulWidget {
|
||||
const ReportWebViewPage({super.key});
|
||||
|
||||
@override
|
||||
ConsumerState<ReportWebViewPage> createState() => _ReportWebViewPageState();
|
||||
}
|
||||
|
||||
class _ReportWebViewPageState extends ConsumerState<ReportWebViewPage> {
|
||||
InAppWebViewController? _webController;
|
||||
double _loadingProgress = 0;
|
||||
String _reportType = 'placementTest';
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeDependencies() {
|
||||
super.didChangeDependencies();
|
||||
// initState 里不能调 GoRouterState.of(context)(会访问 InheritedWidget),
|
||||
// didChangeDependencies 在 initState 之后、build 之前立刻调用,
|
||||
// 赋值时机刚好赶得上 InAppWebView.initialUrlRequest 用 _reportType 拼 URL。
|
||||
final extra =
|
||||
GoRouterState.of(context).extra as Map<String, dynamic>? ?? {};
|
||||
_reportType = (extra['type'] as String?) ?? 'placementTest';
|
||||
}
|
||||
|
||||
/// 拼 H5 壳子的加载 URL(对齐 UniApp reportWebView.vue 的 encodeURIComponent 逻辑)
|
||||
String _buildH5Url() {
|
||||
final token = DioClient.instance.accessToken ?? '';
|
||||
final baseUrl = AppConfig.baseUrl;
|
||||
final safeBottom = 0; // TODO: 计算安全底部距离
|
||||
// 用 Dart Uri 统一编码所有 query param,和 UniApp 的 encodeURIComponent 对齐
|
||||
final h5Uri = Uri.parse(AppConfig.reportUrl);
|
||||
return h5Uri
|
||||
.replace(
|
||||
queryParameters: {
|
||||
'baseURL': baseUrl,
|
||||
'token': token,
|
||||
't': DateTime.now().millisecondsSinceEpoch.toString(),
|
||||
'safeBottom': safeBottom.toString(),
|
||||
'type': _reportType,
|
||||
},
|
||||
)
|
||||
.toString();
|
||||
}
|
||||
|
||||
/// 注入 window.uni JS Bridge 源码(使用 console 通道通信,比 callHandler 更稳)
|
||||
String get _uniBridgeScript {
|
||||
final script = '''
|
||||
(function() {
|
||||
window.uni = window.uni || {};
|
||||
|
||||
// 通过 console.log 发送指令给 Flutter 端 onConsoleMessage 监听
|
||||
function callFlutter(action, url) {
|
||||
console.log('[FLUTTER_BRIDGE] ' + action + ' ' + url);
|
||||
}
|
||||
|
||||
window.uni.switchTab = function(options) {
|
||||
var url = (options && options.url) || '';
|
||||
console.log('[uniBridge] switchTab called, url=' + url);
|
||||
callFlutter('switchTab', url);
|
||||
if (options && options.success) options.success();
|
||||
};
|
||||
window.uni.navigateTo = function(options) {
|
||||
var url = (options && options.url) || '';
|
||||
console.log('[uniBridge] navigateTo called, url=' + url);
|
||||
callFlutter('navigateTo', url);
|
||||
if (options && options.success) options.success();
|
||||
};
|
||||
window.uni.reLaunch = function(options) {
|
||||
var url = (options && options.url) || '';
|
||||
console.log('[uniBridge] reLaunch called, url=' + url);
|
||||
callFlutter('reLaunch', url);
|
||||
if (options && options.success) options.success();
|
||||
};
|
||||
console.log('[uniBridge] window.uni injected via console channel');
|
||||
})();
|
||||
''';
|
||||
return script;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final h5Url = _buildH5Url();
|
||||
talker.debug('ReportWebViewPage loading: $h5Url');
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: Colors.white,
|
||||
appBar: AppBar(
|
||||
backgroundColor: Colors.white,
|
||||
elevation: 0,
|
||||
title: Text('学生报告'),
|
||||
leading: IconButton(
|
||||
icon: const Icon(Icons.arrow_back_ios_new, color: Color(0xFF1D2B47)),
|
||||
onPressed: () => context.canPop() ? context.pop() : context.go('/'),
|
||||
),
|
||||
),
|
||||
body: InAppWebView(
|
||||
initialUrlRequest: URLRequest(url: WebUri(h5Url)),
|
||||
initialSettings: InAppWebViewSettings(
|
||||
javaScriptEnabled: true,
|
||||
allowsInlineMediaPlayback: true,
|
||||
useHybridComposition: true,
|
||||
),
|
||||
// 把 H5 壳子的 console 日志转发到 Flutter talker
|
||||
onConsoleMessage: (controller, consoleMessage) {
|
||||
final levelName = consoleMessage.messageLevel
|
||||
.toString()
|
||||
.split('.')
|
||||
.last;
|
||||
final rawMsg = consoleMessage.message;
|
||||
final msg = '[H5] [$levelName] $rawMsg';
|
||||
if (levelName == 'ERROR') {
|
||||
talker.error(msg);
|
||||
} else {
|
||||
talker.debug(msg);
|
||||
}
|
||||
// 解析 H5 通过 console 发来的跳转指令:
|
||||
// console.log('[FLUTTER_BRIDGE] switchTab', '/pages/tabbar/task/task')
|
||||
// console.log('[FLUTTER_BRIDGE] navigateTo', '/pages/reportPackage/reportComputation/reportComputation')
|
||||
// console.log('[FLUTTER_BRIDGE] reLaunch', '/pages/xxx/yyy')
|
||||
if (rawMsg.startsWith('[FLUTTER_BRIDGE]')) {
|
||||
final parts = rawMsg
|
||||
.substring('[FLUTTER_BRIDGE]'.length)
|
||||
.trim()
|
||||
.split(' ');
|
||||
if (parts.length >= 2) {
|
||||
final action = parts[0];
|
||||
final url = parts.sublist(1).join(' ');
|
||||
final flutterPath = _mapH5Path(url);
|
||||
talker.debug('[consoleBridge] $action $url → $flutterPath');
|
||||
switch (action) {
|
||||
case 'switchTab':
|
||||
if (mounted) context.go(flutterPath);
|
||||
break;
|
||||
case 'navigateTo':
|
||||
if (mounted) context.go(flutterPath);
|
||||
break;
|
||||
case 'reLaunch':
|
||||
if (mounted) context.go(flutterPath);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
onWebViewCreated: (controller) {
|
||||
_webController = controller;
|
||||
_registerJsBridge(controller);
|
||||
},
|
||||
onLoadStop: (controller, url) async {
|
||||
setState(() => _loadingProgress = 1);
|
||||
// 注入 window.uni JS Bridge
|
||||
await controller.evaluateJavascript(source: _uniBridgeScript);
|
||||
},
|
||||
onProgressChanged: (controller, progress) {
|
||||
setState(() => _loadingProgress = progress / 100.0);
|
||||
},
|
||||
),
|
||||
bottomNavigationBar: _loadingProgress < 1.0
|
||||
? LinearProgressIndicator(
|
||||
value: _loadingProgress,
|
||||
backgroundColor: Colors.transparent,
|
||||
valueColor: const AlwaysStoppedAnimation(Color(0xFF3D7DF5)),
|
||||
)
|
||||
: null,
|
||||
);
|
||||
}
|
||||
|
||||
/// H5 壳子传的 uni-app 路径 → Flutter 路由路径映射表
|
||||
///
|
||||
/// H5 壳子里所有 uni.switchTab/navigateTo/reLaunch 都用 uni-app 的路径格式,
|
||||
/// Flutter Bridge 收到后先过这个表转成 Flutter 自己的路由再跳转。
|
||||
static const Map<String, String> _h5PathMap = {
|
||||
// switchTab
|
||||
'/pages/tabbar/task/task': '/',
|
||||
'/pages/tabbar/recite/recite': '/recite',
|
||||
'/pages/tabbar/class/class': '/class',
|
||||
'/pages/tabbar/my/my': '/my',
|
||||
// navigateTo
|
||||
'/pages/reportPackage/reportComputation/reportComputation':
|
||||
'/reportComputation',
|
||||
// reLaunch
|
||||
'/pages/reportPackage/studentInfo/studentInfo': '/studentInfo',
|
||||
'/pages/login/index': '/login',
|
||||
};
|
||||
|
||||
/// 把 H5 uni-app 路径转 Flutter 路由,转不了就原样返回
|
||||
String _mapH5Path(String h5Path) {
|
||||
// 去掉 query 参数再匹配
|
||||
final pathOnly = h5Path.split('?').first;
|
||||
return _h5PathMap[pathOnly] ?? h5Path;
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// JS Bridge:接收 H5 壳子通过 window.uni.switchTab/navigateTo/reLaunch 发起的调用
|
||||
// 统一用 uniBridge 一个 handler,参数里带 name 区分
|
||||
// ============================================================
|
||||
void _registerJsBridge(InAppWebViewController controller) {
|
||||
// addJavaScriptHandler 在 Chrome Web 平台不支持,跳过即可
|
||||
if (kIsWeb) {
|
||||
talker.debug('[uniBridge] Web平台跳过 registerJsBridge');
|
||||
return;
|
||||
}
|
||||
controller.addJavaScriptHandler(
|
||||
handlerName: 'uniBridge',
|
||||
callback: (args) async {
|
||||
// 最顶端先打,任何过滤之前
|
||||
talker.debug('[uniBridge] 收到 callHandler, args=$args');
|
||||
if (args.isEmpty) {
|
||||
talker.debug('[uniBridge] args 为空,return');
|
||||
return;
|
||||
}
|
||||
final payload = args.first;
|
||||
if (payload is! Map) {
|
||||
talker.debug(
|
||||
'[uniBridge] payload 不是 Map,return: ${payload.runtimeType}',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
final name = payload['name'] as String?;
|
||||
final options = payload['options'] as Map<String, dynamic>? ?? {};
|
||||
final url = options['url'] as String? ?? '';
|
||||
final flutterPath = _mapH5Path(url);
|
||||
|
||||
talker.debug('[uniBridge] $name $url → $flutterPath');
|
||||
|
||||
switch (name) {
|
||||
case 'switchTab':
|
||||
await _handleSwitchTab(flutterPath);
|
||||
break;
|
||||
case 'navigateTo':
|
||||
await _handleNavigateTo(flutterPath);
|
||||
break;
|
||||
case 'reLaunch':
|
||||
await _handleReLaunch(flutterPath);
|
||||
break;
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// H5 壳子调 switchTab:直接跳对应 tab
|
||||
Future<void> _handleSwitchTab(String flutterPath) async {
|
||||
if (!mounted) return;
|
||||
context.go(flutterPath);
|
||||
}
|
||||
|
||||
/// H5 壳子调 navigateTo:跳到对应 Flutter 页面
|
||||
Future<void> _handleNavigateTo(String flutterPath) async {
|
||||
if (!mounted) return;
|
||||
context.go(flutterPath);
|
||||
}
|
||||
|
||||
/// H5 壳子调 reLaunch:重建路由栈跳到对应页面
|
||||
Future<void> _handleReLaunch(String flutterPath) async {
|
||||
if (!mounted) return;
|
||||
context.go(flutterPath);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_webController?.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:new_learn/core/api/auth/api.dart';
|
||||
import 'package:new_learn/core/api/report/api.dart';
|
||||
import 'package:new_learn/core/api/report/model.dart';
|
||||
import 'package:new_learn/core/config/app_config.dart';
|
||||
import 'package:new_learn/core/logger/app_talker.dart';
|
||||
import 'package:new_learn/core/network/dio_client.dart';
|
||||
import 'package:new_learn/core/providers/user_provider.dart';
|
||||
|
||||
/// ============================================================
|
||||
/// 【StudentInfoPage】诊断报告欢迎介绍页 —— 对标 Vue studentInfo.vue
|
||||
///
|
||||
/// 路由参数(GoRouteState.extra):
|
||||
/// context.go('/studentInfo', extra: {'type': 'placementTest'});
|
||||
/// - type: placementTest(入门测)| exitTest(出门测)
|
||||
///
|
||||
/// 完整链路:登录成功/全局拦截 → 此页 → H5壳子 → reportComputation(入门测)
|
||||
/// 或 switchTab 首页(出门测)
|
||||
/// ============================================================
|
||||
class StudentInfoPage extends ConsumerStatefulWidget {
|
||||
const StudentInfoPage({super.key});
|
||||
|
||||
@override
|
||||
ConsumerState<StudentInfoPage> createState() => _StudentInfoPageState();
|
||||
}
|
||||
|
||||
class _StudentInfoPageState extends ConsumerState<StudentInfoPage> {
|
||||
UserReportType _report = const UserReportType();
|
||||
bool _loading = true;
|
||||
String _reportType = 'placementTest';
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
final extra = GoRouterState.of(context).extra as Map<String, dynamic>? ?? {};
|
||||
_reportType = (extra['type'] as String?) ?? 'placementTest';
|
||||
_loadReport();
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _loadReport() async {
|
||||
setState(() => _loading = true);
|
||||
try {
|
||||
final isExit = _reportType == 'exitTest';
|
||||
final apiPath = isExit
|
||||
? '/api/v1/UserReport/GetCurrentAfterReport'
|
||||
: '/api/v1/UserReport/GetCurrentReport';
|
||||
talker.debug('studentInfo 调 $apiPath');
|
||||
final report = isExit
|
||||
? await ReportApi.instance.getCurrentAfterReport()
|
||||
: await ReportApi.instance.getCurrentReport();
|
||||
talker.debug(
|
||||
'studentInfo 响应: userName=${report.userName} '
|
||||
'subjectReports.length=${report.subjectReports.length} '
|
||||
'raw=${report.subjectReports.toString()}',
|
||||
);
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_report = report;
|
||||
_loading = false;
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
talker.error('加载报告数据失败', e);
|
||||
if (mounted) setState(() => _loading = false);
|
||||
}
|
||||
}
|
||||
|
||||
/// 按钮点击:subjectReports 为空 → 降级置 false 回首页;否则进 H5 壳子
|
||||
Future<void> _onStart() async {
|
||||
if (_report.subjectReports.isEmpty) {
|
||||
// 降级:只改本地标记,不调后端
|
||||
talker.debug('studentInfo: subjectReports 为空,降级本地置 false');
|
||||
if (_reportType == 'exitTest') {
|
||||
await ref.read(currentUserProvider.notifier).markShowAfterReportFalse();
|
||||
} else {
|
||||
await ref.read(currentUserProvider.notifier).markShowReportFalse();
|
||||
}
|
||||
if (mounted) context.go('/');
|
||||
return;
|
||||
}
|
||||
// 进 H5 壳子
|
||||
context.push('/reportWebView', extra: {
|
||||
'type': _reportType,
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final user = ref.watch(currentUserProvider).value;
|
||||
final userName = _report.userName.isNotEmpty
|
||||
? _report.userName
|
||||
: (user?.userName ?? '');
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: const Color(0xFFF5F8FF),
|
||||
appBar: AppBar(
|
||||
backgroundColor: Colors.transparent,
|
||||
elevation: 0,
|
||||
leading: IconButton(
|
||||
icon: const Icon(Icons.arrow_back_ios_new, color: Color(0xFF1D2B47)),
|
||||
onPressed: () => context.canPop() ? context.pop() : context.go('/'),
|
||||
),
|
||||
),
|
||||
body: _loading
|
||||
? const Center(child: CircularProgressIndicator())
|
||||
: SafeArea(
|
||||
child: Column(
|
||||
children: [
|
||||
// 顶部问候
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 28),
|
||||
child: Row(
|
||||
children: [
|
||||
const Text(
|
||||
'Hi . ',
|
||||
style: TextStyle(
|
||||
fontSize: 28,
|
||||
fontWeight: FontWeight.w900,
|
||||
color: Colors.white,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
userName,
|
||||
style: const TextStyle(
|
||||
fontSize: 28,
|
||||
fontWeight: FontWeight.w900,
|
||||
color: Colors.white,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
// 科目卡片列表
|
||||
Expanded(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.fromLTRB(28, 120, 28, 20),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Padding(
|
||||
padding: EdgeInsets.only(bottom: 12),
|
||||
child: Text(
|
||||
'诊断科目分析',
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: Color(0xFF1D2B47),
|
||||
),
|
||||
),
|
||||
),
|
||||
Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
child: _report.subjectReports.isEmpty
|
||||
? const Center(
|
||||
child: Text(
|
||||
'暂无数据',
|
||||
style: TextStyle(color: Color(0xFF687FAD)),
|
||||
),
|
||||
)
|
||||
: Wrap(
|
||||
spacing: 10,
|
||||
runSpacing: 10,
|
||||
children: _report.subjectReports
|
||||
.map((s) => _SubjectCard(
|
||||
subject: s,
|
||||
))
|
||||
.toList(),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
// 底部按钮
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(29, 20, 29, 20),
|
||||
child: SizedBox(
|
||||
width: double.infinity,
|
||||
height: 50,
|
||||
child: ElevatedButton(
|
||||
onPressed: _onStart,
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: const Color(0xFF3D7DF5),
|
||||
foregroundColor: Colors.white,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(25),
|
||||
),
|
||||
elevation: 0,
|
||||
),
|
||||
child: const Text(
|
||||
'开启智能诊断报告',
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SubjectCard extends StatelessWidget {
|
||||
const _SubjectCard({required this.subject});
|
||||
final SubjectReportType subject;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
width: 72,
|
||||
height: 88,
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
gradient: const LinearGradient(
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
colors: [Color(0xFFF5F8FF), Color(0xFFE6EEFF)],
|
||||
),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: subject.icon.isNotEmpty
|
||||
? Image.network(
|
||||
subject.icon,
|
||||
width: 40,
|
||||
height: 40,
|
||||
fit: BoxFit.cover,
|
||||
errorBuilder: (_, __, ___) => const Icon(
|
||||
Icons.menu_book,
|
||||
size: 40,
|
||||
color: Color(0xFF3D7DF5),
|
||||
),
|
||||
)
|
||||
: const Icon(
|
||||
Icons.menu_book,
|
||||
size: 40,
|
||||
color: Color(0xFF3D7DF5),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
subject.subjectName,
|
||||
style: const TextStyle(
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.w500,
|
||||
color: Color(0xFF1D2B47),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user