修复工作人员端令牌失效后的登录恢复
This commit is contained in:
32
apps/service_app/lib/app/auth_navigation.dart
Normal file
32
apps/service_app/lib/app/auth_navigation.dart
Normal file
@@ -0,0 +1,32 @@
|
||||
// 功能描述:提供工作人员端鉴权地址构造与站内回跳地址校验。
|
||||
// 版本:1.0.0
|
||||
|
||||
/// 构造登录地址,并安全携带原目标页和会话失效原因。
|
||||
String buildAuthLocation({
|
||||
String? redirectTarget,
|
||||
bool sessionExpired = false,
|
||||
}) {
|
||||
final safeTarget = sanitizeRedirectTarget(redirectTarget);
|
||||
final query = <String, String>{
|
||||
'redirect': ?safeTarget,
|
||||
if (sessionExpired) 'reason': 'expired',
|
||||
};
|
||||
return Uri(
|
||||
path: '/login',
|
||||
queryParameters: query.isEmpty ? null : query,
|
||||
).toString();
|
||||
}
|
||||
|
||||
/// 只接受站内绝对路径,阻止外部地址和登录页形成重定向循环。
|
||||
String? sanitizeRedirectTarget(String? value) {
|
||||
final candidate = value?.trim() ?? '';
|
||||
if (candidate.isEmpty) return null;
|
||||
|
||||
final uri = Uri.tryParse(candidate);
|
||||
if (uri == null || uri.hasScheme || uri.hasAuthority || !uri.path.startsWith('/')) {
|
||||
return null;
|
||||
}
|
||||
if (uri.path.startsWith('//') || uri.path.contains(r'\')) return null;
|
||||
if (uri.path == '/login') return null;
|
||||
return uri.toString();
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
// 功能描述:装配工作人员端依赖,并统一管理登录、退出和失效会话。
|
||||
// 版本:1.1.0
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
@@ -8,7 +10,7 @@ import '../data/services/location_service.dart';
|
||||
import '../data/services/secure_session_store.dart';
|
||||
|
||||
class AppDependencies {
|
||||
AppDependencies._({
|
||||
AppDependencies({
|
||||
required this.session,
|
||||
required this.repository,
|
||||
required this.drafts,
|
||||
@@ -22,15 +24,19 @@ class AppDependencies {
|
||||
final store = SecureSessionStore();
|
||||
final session = StaffSession(store);
|
||||
await session.restore();
|
||||
final api = ApiClient(() => session.token);
|
||||
return AppDependencies._(
|
||||
final authenticatedApi = ApiClient(
|
||||
() => session.token,
|
||||
onUnauthorized: session.invalidate,
|
||||
);
|
||||
return AppDependencies(
|
||||
session: session,
|
||||
repository: ServiceRepository(api, GeolocatorLocationService()),
|
||||
repository: ServiceRepository(authenticatedApi, GeolocatorLocationService()),
|
||||
drafts: EncryptedDraftStore(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 管理工作人员令牌、身份、角色、设备标识及会话失效通知。
|
||||
class StaffSession extends ChangeNotifier {
|
||||
StaffSession(this._store);
|
||||
|
||||
@@ -39,24 +45,29 @@ class StaffSession extends ChangeNotifier {
|
||||
static const _identityKey = 'service_app_identity';
|
||||
static const _roleKey = 'service_app_role';
|
||||
static const _deviceKey = 'service_app_device';
|
||||
final SecureSessionStore _store;
|
||||
final SessionStore _store;
|
||||
|
||||
String _token = '';
|
||||
String _identity = '';
|
||||
String _roleCode = '';
|
||||
String _deviceIdentity = '';
|
||||
bool _expired = false;
|
||||
Future<void> _pendingClear = Future<void>.value();
|
||||
|
||||
String get token => _token;
|
||||
String get identity => _identity;
|
||||
String get roleCode => _roleCode;
|
||||
String get deviceIdentity => _deviceIdentity;
|
||||
bool get isAuthenticated => _token.isNotEmpty;
|
||||
bool get hasExpired => _expired;
|
||||
|
||||
/// 从安全存储恢复会话上下文;是否有效由后续受保护接口响应确认。
|
||||
Future<void> restore() async {
|
||||
_token = await _store.read(_tokenKey) ?? '';
|
||||
_identity = await _store.read(_identityKey) ?? '';
|
||||
_roleCode = await _store.read(_roleKey) ?? '';
|
||||
_deviceIdentity = await _store.read(_deviceKey) ?? '';
|
||||
_expired = false;
|
||||
if (_deviceIdentity.isEmpty) {
|
||||
_deviceIdentity = const Uuid().v7();
|
||||
await _store.write(_deviceKey, _deviceIdentity);
|
||||
@@ -72,15 +83,22 @@ class StaffSession extends ChangeNotifier {
|
||||
body: {'phone': phone, 'mode': 'password', 'password': password},
|
||||
),
|
||||
);
|
||||
_token = details['access_token'] as String? ?? '';
|
||||
_identity = details['identity'] as String? ?? '';
|
||||
_roleCode = details['role_code'] as String? ?? '';
|
||||
if (_token.isEmpty || _identity.isEmpty || _roleCode.isEmpty) {
|
||||
final token = details['access_token'] as String? ?? '';
|
||||
final identity = details['identity'] as String? ?? '';
|
||||
final roleCode = details['role_code'] as String? ?? '';
|
||||
if (token.isEmpty || identity.isEmpty || roleCode.isEmpty) {
|
||||
throw const ApiException(500, '工作人员登录上下文缺失');
|
||||
}
|
||||
await _store.write(_tokenKey, _token);
|
||||
await _store.write(_identityKey, _identity);
|
||||
await _store.write(_roleKey, _roleCode);
|
||||
|
||||
// 等待旧会话清理结束,避免迟到的删除任务误删刚写入的新会话。
|
||||
await _pendingClear;
|
||||
await _store.write(_tokenKey, token);
|
||||
await _store.write(_identityKey, identity);
|
||||
await _store.write(_roleKey, roleCode);
|
||||
_token = token;
|
||||
_identity = identity;
|
||||
_roleCode = roleCode;
|
||||
_expired = false;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
@@ -88,9 +106,33 @@ class StaffSession extends ChangeNotifier {
|
||||
_token = '';
|
||||
_identity = '';
|
||||
_roleCode = '';
|
||||
await _store.delete(_tokenKey);
|
||||
await _store.delete(_identityKey);
|
||||
await _store.delete(_roleKey);
|
||||
_expired = false;
|
||||
notifyListeners();
|
||||
_pendingClear = _clearStoredSession();
|
||||
await _pendingClear;
|
||||
}
|
||||
|
||||
/// 仅当服务端拒绝的仍是当前令牌时,使会话失效并通知路由。
|
||||
void invalidate(String rejectedToken) {
|
||||
if (rejectedToken.isEmpty || rejectedToken != _token || _expired) return;
|
||||
|
||||
_token = '';
|
||||
_identity = '';
|
||||
_roleCode = '';
|
||||
_expired = true;
|
||||
notifyListeners();
|
||||
_pendingClear = _clearStoredSession();
|
||||
}
|
||||
|
||||
/// 尽力删除会话字段并保留设备标识;单项失败不得阻塞返回登录页。
|
||||
Future<void> _clearStoredSession() async {
|
||||
for (final key in const [_tokenKey, _identityKey, _roleKey]) {
|
||||
try {
|
||||
await _store.delete(key);
|
||||
} catch (error, stackTrace) {
|
||||
debugPrint('清理工作人员失效会话失败($key):$error');
|
||||
debugPrintStack(stackTrace: stackTrace);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// 功能描述:配置工作人员端路由、鉴权守卫及登录后安全回跳。
|
||||
// 版本:1.1.0
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
@@ -7,21 +9,35 @@ import '../ui/features/preflight/preflight_page.dart';
|
||||
import '../ui/features/profile/profile_page.dart';
|
||||
import '../ui/features/work/work_detail_page.dart';
|
||||
import '../ui/features/work/work_list_page.dart';
|
||||
import 'auth_navigation.dart';
|
||||
import 'dependencies.dart';
|
||||
|
||||
GoRouter createRouter(AppDependencies dependencies) => GoRouter(
|
||||
initialLocation: '/preflight',
|
||||
GoRouter createRouter(
|
||||
AppDependencies dependencies, {
|
||||
String initialLocation = '/preflight',
|
||||
}) => GoRouter(
|
||||
initialLocation: initialLocation,
|
||||
refreshListenable: dependencies.session,
|
||||
redirect: (context, state) {
|
||||
final login = state.matchedLocation == '/login';
|
||||
if (!dependencies.session.isAuthenticated && !login) return '/login';
|
||||
if (dependencies.session.isAuthenticated && login) return '/preflight';
|
||||
if (!dependencies.session.isAuthenticated && !login) {
|
||||
return buildAuthLocation(
|
||||
redirectTarget: state.uri.toString(),
|
||||
sessionExpired: dependencies.session.hasExpired,
|
||||
);
|
||||
}
|
||||
if (dependencies.session.isAuthenticated && login) {
|
||||
return sanitizeRedirectTarget(state.uri.queryParameters['redirect']) ?? '/preflight';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
routes: [
|
||||
GoRoute(
|
||||
path: '/login',
|
||||
builder: (context, state) => LoginPage(session: dependencies.session),
|
||||
builder: (context, state) => LoginPage(
|
||||
session: dependencies.session,
|
||||
showSessionExpiredMessage: state.uri.queryParameters['reason'] == 'expired',
|
||||
),
|
||||
),
|
||||
GoRoute(
|
||||
path: '/preflight',
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// 功能描述:封装工作人员端 HTTP 请求,并将服务端错误转换为安全、可读的中文提示。
|
||||
// 版本:1.1.0
|
||||
// 版本:1.2.0
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:http/http.dart' as http;
|
||||
@@ -84,20 +84,33 @@ class ApiException implements Exception {
|
||||
String toString() => message;
|
||||
}
|
||||
|
||||
/// 表示鉴权会话已经失效;页面层应等待路由跳转,不再展示普通网络错误。
|
||||
class SessionExpiredException extends ApiException {
|
||||
const SessionExpiredException() : super(401, '登录状态已失效,请重新登录');
|
||||
}
|
||||
|
||||
/// 接收被服务端拒绝的请求令牌,用于安全地失效对应会话。
|
||||
typedef UnauthorizedCallback = void Function(String rejectedToken);
|
||||
|
||||
/// 负责工作人员端统一 HTTP 请求、鉴权头和响应解析。
|
||||
class ApiClient {
|
||||
ApiClient(this._tokenProvider, {http.Client? client, String? baseUrl})
|
||||
: _client = client ?? http.Client(),
|
||||
baseUrl =
|
||||
baseUrl ??
|
||||
const String.fromEnvironment(
|
||||
'API_BASE_URL',
|
||||
defaultValue: 'http://10.0.2.2:12426',
|
||||
);
|
||||
ApiClient(
|
||||
this._tokenProvider, {
|
||||
http.Client? client,
|
||||
String? baseUrl,
|
||||
this.onUnauthorized,
|
||||
}) : _client = client ?? http.Client(),
|
||||
baseUrl =
|
||||
baseUrl ??
|
||||
const String.fromEnvironment(
|
||||
'API_BASE_URL',
|
||||
defaultValue: 'http://10.0.2.2:12426',
|
||||
);
|
||||
|
||||
final String baseUrl;
|
||||
final String Function() _tokenProvider;
|
||||
final http.Client _client;
|
||||
final UnauthorizedCallback? onUnauthorized;
|
||||
|
||||
Future<Object?> get(String path, {bool authenticated = true}) =>
|
||||
_send('GET', path, authenticated: authenticated);
|
||||
@@ -116,7 +129,8 @@ class ApiClient {
|
||||
'POST',
|
||||
Uri.parse('$baseUrl/upload/file'),
|
||||
);
|
||||
request.headers['authorization'] = _tokenProvider();
|
||||
final requestToken = _tokenProvider();
|
||||
if (requestToken.isNotEmpty) request.headers['authorization'] = requestToken;
|
||||
request.fields['declared_content_type'] = contentType;
|
||||
request.files.add(
|
||||
http.MultipartFile.fromBytes(
|
||||
@@ -126,7 +140,11 @@ class ApiClient {
|
||||
),
|
||||
);
|
||||
final response = await _sendRequest(request);
|
||||
final details = _decode(response);
|
||||
final details = _decode(
|
||||
response,
|
||||
authenticated: true,
|
||||
requestToken: requestToken,
|
||||
);
|
||||
return jsonMap(details)['uri'] as String? ?? '';
|
||||
}
|
||||
|
||||
@@ -138,15 +156,21 @@ class ApiClient {
|
||||
}) async {
|
||||
final request = http.Request(method, Uri.parse('$baseUrl$path'));
|
||||
request.headers['accept'] = 'application/json';
|
||||
if (authenticated && _tokenProvider().isNotEmpty) {
|
||||
request.headers['authorization'] = _tokenProvider();
|
||||
var requestToken = '';
|
||||
if (authenticated) {
|
||||
requestToken = _tokenProvider();
|
||||
if (requestToken.isNotEmpty) request.headers['authorization'] = requestToken;
|
||||
}
|
||||
if (body != null) {
|
||||
request.headers['content-type'] = 'application/json; charset=UTF-8';
|
||||
request.body = jsonEncode(body);
|
||||
}
|
||||
final response = await _sendRequest(request);
|
||||
return _decode(response);
|
||||
return _decode(
|
||||
response,
|
||||
authenticated: authenticated,
|
||||
requestToken: requestToken,
|
||||
);
|
||||
}
|
||||
|
||||
/// 发送请求并统一处理网络连接异常。
|
||||
@@ -159,7 +183,14 @@ class ApiClient {
|
||||
}
|
||||
|
||||
/// 解析统一响应结构,并按错误码生成中文提示。
|
||||
Object? _decode(http.Response response) {
|
||||
Object? _decode(
|
||||
http.Response response, {
|
||||
required bool authenticated,
|
||||
required String requestToken,
|
||||
}) {
|
||||
if (authenticated && response.statusCode == 401 && requestToken.isNotEmpty) {
|
||||
_rejectSession(requestToken);
|
||||
}
|
||||
if (response.statusCode < 200 || response.statusCode >= 300) {
|
||||
throw ApiException(response.statusCode, '网络请求失败(${response.statusCode})');
|
||||
}
|
||||
@@ -174,6 +205,9 @@ class ApiClient {
|
||||
}
|
||||
final code = (decoded['code'] as num?)?.toInt() ?? 500;
|
||||
if (code != 0) {
|
||||
if (authenticated && requestToken.isNotEmpty && _isAuthenticationFailure(code)) {
|
||||
_rejectSession(requestToken);
|
||||
}
|
||||
throw ApiException(
|
||||
code,
|
||||
localizeApiErrorMessage(code, decoded['message'] as String?),
|
||||
@@ -181,8 +215,17 @@ class ApiClient {
|
||||
}
|
||||
return decoded['details'];
|
||||
}
|
||||
|
||||
/// 通知会话层并抛出专用异常,避免页面把鉴权失败误报为网络问题。
|
||||
Never _rejectSession(String rejectedToken) {
|
||||
onUnauthorized?.call(rejectedToken);
|
||||
throw const SessionExpiredException();
|
||||
}
|
||||
}
|
||||
|
||||
/// 判断服务端稳定错误码是否表示登录会话无效。
|
||||
bool _isAuthenticationFailure(int code) => (code >= 1301 && code <= 1314) || code == 1715;
|
||||
|
||||
Map<String, Object?> jsonMap(Object? value) {
|
||||
if (value is Map<String, Object?>) return value;
|
||||
if (value is Map) return value.map((key, item) => MapEntry(key.toString(), item));
|
||||
|
||||
@@ -1,12 +1,29 @@
|
||||
// 功能描述:封装工作人员端会话上下文的安全持久化接口与平台实现。
|
||||
// 版本:1.1.0
|
||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||
|
||||
class SecureSessionStore {
|
||||
/// 定义工作人员会话持久化能力,便于会话逻辑隔离具体存储实现。
|
||||
abstract interface class SessionStore {
|
||||
Future<String?> read(String key);
|
||||
|
||||
Future<void> write(String key, String value);
|
||||
|
||||
Future<void> delete(String key);
|
||||
}
|
||||
|
||||
/// 使用平台安全存储保存工作人员会话上下文。
|
||||
class SecureSessionStore implements SessionStore {
|
||||
SecureSessionStore({FlutterSecureStorage? storage})
|
||||
: _storage = storage ?? const FlutterSecureStorage();
|
||||
|
||||
final FlutterSecureStorage _storage;
|
||||
|
||||
@override
|
||||
Future<String?> read(String key) => _storage.read(key: key);
|
||||
|
||||
@override
|
||||
Future<void> write(String key, String value) => _storage.write(key: key, value: value);
|
||||
|
||||
@override
|
||||
Future<void> delete(String key) => _storage.delete(key: key);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// 功能描述:提供工作人员端手机号密码登录界面及本地输入校验。
|
||||
// 版本:1.2.0
|
||||
// 版本:1.3.0
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../app/dependencies.dart';
|
||||
@@ -7,9 +7,14 @@ import '../../../data/services/api_client.dart';
|
||||
|
||||
/// 工作人员端手机号密码登录页面。
|
||||
class LoginPage extends StatefulWidget {
|
||||
const LoginPage({required this.session, super.key});
|
||||
const LoginPage({
|
||||
required this.session,
|
||||
this.showSessionExpiredMessage = false,
|
||||
super.key,
|
||||
});
|
||||
|
||||
final StaffSession session;
|
||||
final bool showSessionExpiredMessage;
|
||||
|
||||
@override
|
||||
State<LoginPage> createState() => _LoginPageState();
|
||||
@@ -29,6 +34,14 @@ class _LoginPageState extends State<LoginPage> {
|
||||
String? _passwordError;
|
||||
bool _obscurePassword = true;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
if (widget.showSessionExpiredMessage) {
|
||||
_error = '登录状态已失效,请重新登录';
|
||||
}
|
||||
}
|
||||
|
||||
/// 校验手机号和密码,通过后再提交登录请求。
|
||||
Future<void> _login() async {
|
||||
final phone = _phone.text.trim();
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// 功能描述:管理工作人员现场取证、加密草稿和安全提交。
|
||||
// 版本:1.1.0
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:image_picker/image_picker.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
@@ -5,6 +7,7 @@ import 'package:uuid/uuid.dart';
|
||||
import '../../../app/dependencies.dart';
|
||||
import '../../../data/offline/encrypted_draft_store.dart';
|
||||
import '../../../data/repositories/service_repository.dart';
|
||||
import '../../../data/services/api_client.dart';
|
||||
import '../../core/widgets.dart';
|
||||
|
||||
class EvidencePage extends StatefulWidget {
|
||||
@@ -138,6 +141,8 @@ class _EvidencePageState extends State<EvidencePage> {
|
||||
widget.taskIdentity,
|
||||
);
|
||||
if (mounted) Navigator.pop(context, true);
|
||||
} on SessionExpiredException {
|
||||
return;
|
||||
} catch (error) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
// 功能描述:展示工作人员作业准入检查,并安全处理刷新和会话失效。
|
||||
// 版本:1.1.0
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../../../app/dependencies.dart';
|
||||
import '../../../data/repositories/service_repository.dart';
|
||||
import '../../../data/services/api_client.dart';
|
||||
import '../../../domain/models/service_models.dart';
|
||||
import '../../core/widgets.dart';
|
||||
|
||||
@@ -26,11 +29,21 @@ class _PreflightPageState extends State<PreflightPage> {
|
||||
_future = widget.repository.preflight();
|
||||
}
|
||||
|
||||
/// 创建新的加载任务,并在同步状态回调中替换页面 Future。
|
||||
void _reload() {
|
||||
final future = widget.repository.preflight();
|
||||
setState(() {
|
||||
_future = future;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _attendance(String action) async {
|
||||
setState(() => _busy = true);
|
||||
try {
|
||||
await widget.repository.attendance(action, widget.session.deviceIdentity);
|
||||
setState(() => _future = widget.repository.preflight());
|
||||
if (mounted) _reload();
|
||||
} on SessionExpiredException {
|
||||
return;
|
||||
} catch (error) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(error.toString())));
|
||||
@@ -48,10 +61,13 @@ class _PreflightPageState extends State<PreflightPage> {
|
||||
builder: (context, snapshot) {
|
||||
if (!snapshot.hasData) {
|
||||
if (snapshot.hasError) {
|
||||
if (snapshot.error is SessionExpiredException) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
return MessageState(
|
||||
title: '作业检查加载失败',
|
||||
description: '请检查网络后重新加载',
|
||||
onRetry: () => setState(() => _future = widget.repository.preflight()),
|
||||
onRetry: _reload,
|
||||
);
|
||||
}
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
// 功能描述:展示工作人员资料、钱包和草稿状态,并安全处理刷新与退出。
|
||||
// 版本:1.1.0
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../../../app/dependencies.dart';
|
||||
import '../../../data/offline/encrypted_draft_store.dart';
|
||||
import '../../../data/repositories/service_repository.dart';
|
||||
import '../../../data/services/api_client.dart';
|
||||
import '../../../domain/models/service_models.dart';
|
||||
import '../../core/widgets.dart';
|
||||
|
||||
@@ -38,6 +41,14 @@ class _ProfilePageState extends State<ProfilePage> {
|
||||
await widget.drafts.count(widget.session.identity),
|
||||
);
|
||||
|
||||
/// 创建新的加载任务,并在同步状态回调中替换页面 Future。
|
||||
void _reload() {
|
||||
final future = _load();
|
||||
setState(() {
|
||||
_future = future;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _logout(int draftCount) async {
|
||||
if (draftCount > 0) {
|
||||
final discard = await showDialog<bool>(
|
||||
@@ -66,10 +77,13 @@ class _ProfilePageState extends State<ProfilePage> {
|
||||
builder: (context, snapshot) {
|
||||
if (!snapshot.hasData) {
|
||||
if (snapshot.hasError) {
|
||||
if (snapshot.error is SessionExpiredException) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
return MessageState(
|
||||
title: '工作台信息加载失败',
|
||||
description: '请检查网络后重新加载',
|
||||
onRetry: () => setState(() => _future = _load()),
|
||||
onRetry: _reload,
|
||||
);
|
||||
}
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// 功能描述:展示工作人员任务详情,并安全处理业务操作、刷新和会话失效。
|
||||
// 版本:1.1.0
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:image_picker/image_picker.dart';
|
||||
@@ -6,6 +8,7 @@ import 'package:uuid/uuid.dart';
|
||||
import '../../../app/dependencies.dart';
|
||||
import '../../../data/offline/encrypted_draft_store.dart';
|
||||
import '../../../data/repositories/service_repository.dart';
|
||||
import '../../../data/services/api_client.dart';
|
||||
import '../../../domain/models/service_models.dart';
|
||||
import '../../core/widgets.dart';
|
||||
|
||||
@@ -41,6 +44,14 @@ class _WorkDetailPageState extends State<WorkDetailPage> {
|
||||
? widget.repository.deliveryDetail(widget.identity)
|
||||
: widget.repository.ticketDetail(widget.identity);
|
||||
|
||||
/// 创建新的加载任务,并在同步状态回调中替换页面 Future。
|
||||
void _reload() {
|
||||
final future = _load();
|
||||
setState(() {
|
||||
_future = future;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _run(
|
||||
Future<void> Function(WorkItem) action,
|
||||
WorkItem item,
|
||||
@@ -48,7 +59,9 @@ class _WorkDetailPageState extends State<WorkDetailPage> {
|
||||
setState(() => _busy = true);
|
||||
try {
|
||||
await action(item);
|
||||
setState(() => _future = _load());
|
||||
if (mounted) _reload();
|
||||
} on SessionExpiredException {
|
||||
return;
|
||||
} catch (error) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(
|
||||
@@ -152,7 +165,9 @@ class _WorkDetailPageState extends State<WorkDetailPage> {
|
||||
proofFile: temporaryFile,
|
||||
);
|
||||
await widget.drafts.deleteDraft(widget.session.identity, item.identity);
|
||||
if (mounted) setState(() => _future = _load());
|
||||
if (mounted) _reload();
|
||||
} on SessionExpiredException {
|
||||
return;
|
||||
} catch (error) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(
|
||||
@@ -175,10 +190,13 @@ class _WorkDetailPageState extends State<WorkDetailPage> {
|
||||
builder: (context, snapshot) {
|
||||
if (!snapshot.hasData) {
|
||||
if (snapshot.hasError) {
|
||||
if (snapshot.error is SessionExpiredException) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
return MessageState(
|
||||
title: '任务详情加载失败',
|
||||
description: '请检查网络后重新加载',
|
||||
onRetry: () => setState(() => _future = _load()),
|
||||
onRetry: _reload,
|
||||
);
|
||||
}
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
@@ -292,7 +310,7 @@ class _WorkDetailPageState extends State<WorkDetailPage> {
|
||||
final changed = await context.push<bool>(
|
||||
'/tasks/${item.identity}/evidence',
|
||||
);
|
||||
if (changed == true) setState(() => _future = _load());
|
||||
if (changed == true && mounted) _reload();
|
||||
},
|
||||
icon: const Icon(Icons.fact_check_outlined),
|
||||
label: const Text('现场取证与提交'),
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
// 功能描述:管理工作人员任务列表数据,并将会话失效交给统一路由处理。
|
||||
// 版本:1.1.0
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../../../data/repositories/service_repository.dart';
|
||||
import '../../../data/services/api_client.dart';
|
||||
import '../../../domain/models/service_models.dart';
|
||||
|
||||
class WorkListViewModel extends ChangeNotifier {
|
||||
@@ -27,7 +30,8 @@ class WorkListViewModel extends ChangeNotifier {
|
||||
.where((item) => completed ? item.status == 23 : item.status != 23 && item.status != 22)
|
||||
.toList();
|
||||
} catch (error) {
|
||||
_error = error;
|
||||
// 会话失效由统一路由接管,不在任务列表重复展示网络错误。
|
||||
if (error is! SessionExpiredException) _error = error;
|
||||
} finally {
|
||||
_loading = false;
|
||||
notifyListeners();
|
||||
|
||||
Reference in New Issue
Block a user