feat(client): 网络恢复自动刷新 + 离线嗅探 + 连通性感知登录
网络嗅探与自动恢复: - ConnectivityNotifier:在线时 30s 检测,离线时切换为 1min 嗅探 - 新增 networkRecoveryCountProvider:网络恢复时自增,各数据 provider 通过 ref.watch 实现自动重新加载 - inventory/product/stock_in/stock_out/partner provider 均已接入 FutureBuilder 类屏幕: - finance_screen + batch_tracking_screen 通过 ref.listen 监听恢复事件 修复问题 1:API 超时 10s/30s → 5s/15s,减少无网络时等待 修复问题 2:offline banner 文字由"写操作已禁用"改为实际行为描述 连通性感知: - app 启动时(_AppBootstrap)立即 forceCheck,路由跳转前状态已就绪 - 登录页:watch connectivityProvider,离线时显示警告 banner - 登录按钮:离线状态下直接提示,不等待超时 测试: - login_screen_test + login_flow_test 通过 ConnectivityNotifier(skipInit: true) 覆盖 provider,避免测试环境中 pending HTTP timer Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -8,8 +8,8 @@ import '../../providers/connectivity_provider.dart';
|
||||
/// Public Dio instance for unauthenticated calls (login / refresh)
|
||||
final _publicDio = Dio(BaseOptions(
|
||||
baseUrl: AppConfig.apiBaseUrl,
|
||||
connectTimeout: const Duration(seconds: 10),
|
||||
receiveTimeout: const Duration(seconds: 30),
|
||||
connectTimeout: const Duration(seconds: 5),
|
||||
receiveTimeout: const Duration(seconds: 15),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
));
|
||||
|
||||
@@ -52,8 +52,8 @@ class ApiClient {
|
||||
}) {
|
||||
_dio = Dio(BaseOptions(
|
||||
baseUrl: AppConfig.apiBaseUrl,
|
||||
connectTimeout: const Duration(seconds: 10),
|
||||
receiveTimeout: const Duration(seconds: 30),
|
||||
connectTimeout: const Duration(seconds: 5),
|
||||
receiveTimeout: const Duration(seconds: 15),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
if (token != null) 'Authorization': 'Bearer $token',
|
||||
|
||||
@@ -5,6 +5,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'core/auth/auth_state.dart';
|
||||
import 'core/router/app_router.dart';
|
||||
import 'core/theme/app_theme.dart';
|
||||
import 'providers/connectivity_provider.dart';
|
||||
|
||||
void main() {
|
||||
FlutterError.onError = (details) {
|
||||
@@ -57,6 +58,8 @@ class _AppBootstrapState extends ConsumerState<_AppBootstrap> {
|
||||
|
||||
Future<void> _init() async {
|
||||
await ref.read(authStateProvider.notifier).restore();
|
||||
// 启动时立即做一次连通性检测,确保 connectivityProvider 状态在路由跳转前已就绪
|
||||
await ref.read(connectivityProvider.notifier).forceCheck();
|
||||
if (mounted) setState(() => _ready = true);
|
||||
}
|
||||
|
||||
|
||||
@@ -3,34 +3,67 @@ import 'package:dio/dio.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import '../core/config/app_config.dart';
|
||||
|
||||
/// 每次从离线恢复到在线时自增。
|
||||
/// 数据 provider 通过 watch 此值实现网络恢复后自动刷新。
|
||||
final networkRecoveryCountProvider = StateProvider<int>((ref) => 0);
|
||||
|
||||
final connectivityProvider =
|
||||
StateNotifierProvider<ConnectivityNotifier, bool>((ref) {
|
||||
return ConnectivityNotifier();
|
||||
return ConnectivityNotifier(
|
||||
onRecovered: () {
|
||||
ref.read(networkRecoveryCountProvider.notifier).update((s) => s + 1);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
class ConnectivityNotifier extends StateNotifier<bool> {
|
||||
ConnectivityNotifier() : super(true) {
|
||||
_check(); // immediate first check
|
||||
_timer = Timer.periodic(const Duration(seconds: 30), (_) => _check());
|
||||
final void Function()? onRecovered;
|
||||
|
||||
ConnectivityNotifier({this.onRecovered, bool skipInit = false}) : super(true) {
|
||||
if (!skipInit) {
|
||||
_check();
|
||||
_startOnlineTimer();
|
||||
}
|
||||
}
|
||||
|
||||
Timer? _timer;
|
||||
|
||||
// Dedicated lightweight Dio — short timeouts, no interceptors
|
||||
// 独立轻量 Dio:短超时,无拦截器
|
||||
final _dio = Dio(BaseOptions(
|
||||
connectTimeout: const Duration(seconds: 3),
|
||||
receiveTimeout: const Duration(seconds: 3),
|
||||
));
|
||||
|
||||
/// 立即触发一次检测(供外部调用,如 API 请求失败时)
|
||||
/// 在线时:每 30 秒检测一次
|
||||
void _startOnlineTimer() {
|
||||
_timer?.cancel();
|
||||
_timer = Timer.periodic(const Duration(seconds: 30), (_) => _check());
|
||||
}
|
||||
|
||||
/// 离线时:每 1 分钟嗅探一次,降低频率节省资源
|
||||
void _startOfflineTimer() {
|
||||
_timer?.cancel();
|
||||
_timer = Timer.periodic(const Duration(minutes: 1), (_) => _check());
|
||||
}
|
||||
|
||||
/// 立即触发一次检测(供外部调用,如 API 请求失败 / 启动时)
|
||||
Future<void> forceCheck() => _check();
|
||||
|
||||
Future<void> _check() async {
|
||||
try {
|
||||
await _dio.get(AppConfig.healthUrl);
|
||||
if (!state) state = true;
|
||||
if (!state) {
|
||||
// 离线 → 在线:切回高频检测,广播恢复事件
|
||||
state = true;
|
||||
onRecovered?.call();
|
||||
_startOnlineTimer();
|
||||
}
|
||||
} catch (_) {
|
||||
if (state) state = false;
|
||||
if (state) {
|
||||
// 在线 → 离线:切换为低频嗅探
|
||||
state = false;
|
||||
_startOfflineTimer();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import '../core/auth/auth_state.dart';
|
||||
import '../core/models/page_result.dart';
|
||||
import '../models/inventory.dart';
|
||||
import '../repositories/inventory_repository.dart';
|
||||
import 'connectivity_provider.dart';
|
||||
|
||||
final inventoryRepositoryProvider = Provider<InventoryRepository>((ref) {
|
||||
return InventoryRepository(ref.watch(apiClientProvider));
|
||||
@@ -23,6 +24,7 @@ class InventoryListNotifier extends AsyncNotifier<PageResult<Inventory>> {
|
||||
@override
|
||||
Future<PageResult<Inventory>> build() async {
|
||||
ref.watch(authStateProvider.select((s) => s.user?.shopId));
|
||||
ref.watch(networkRecoveryCountProvider); // 网络恢复时自动刷新
|
||||
try {
|
||||
final result = await _fetch();
|
||||
_cache = result;
|
||||
@@ -86,6 +88,7 @@ class InventoryLogNotifier extends AsyncNotifier<PageResult<InventoryLog>> {
|
||||
@override
|
||||
Future<PageResult<InventoryLog>> build() async {
|
||||
ref.watch(authStateProvider.select((s) => s.user?.shopId));
|
||||
ref.watch(networkRecoveryCountProvider);
|
||||
try {
|
||||
final result = await _fetch();
|
||||
_cache = result;
|
||||
|
||||
@@ -4,6 +4,7 @@ import '../core/auth/auth_state.dart';
|
||||
import '../core/models/page_result.dart';
|
||||
import '../models/partner.dart';
|
||||
import '../repositories/partner_repository.dart';
|
||||
import 'connectivity_provider.dart';
|
||||
|
||||
final partnerRepositoryProvider = Provider<PartnerRepository>((ref) {
|
||||
return PartnerRepository(ref.watch(apiClientProvider));
|
||||
@@ -32,6 +33,7 @@ class PartnerListNotifier extends AsyncNotifier<PageResult<Partner>> {
|
||||
@override
|
||||
Future<PageResult<Partner>> build() async {
|
||||
ref.watch(authStateProvider.select((s) => s.user?.shopId));
|
||||
ref.watch(networkRecoveryCountProvider);
|
||||
try {
|
||||
final result = await _fetch();
|
||||
_cache = result;
|
||||
|
||||
@@ -4,6 +4,7 @@ import '../core/auth/auth_state.dart';
|
||||
import '../core/models/page_result.dart';
|
||||
import '../models/product.dart';
|
||||
import '../repositories/product_repository.dart';
|
||||
import 'connectivity_provider.dart';
|
||||
|
||||
final productRepositoryProvider = Provider<ProductRepository>((ref) {
|
||||
return ProductRepository(ref.watch(apiClientProvider));
|
||||
@@ -23,6 +24,7 @@ class ProductListNotifier extends AsyncNotifier<PageResult<Product>> {
|
||||
@override
|
||||
Future<PageResult<Product>> build() async {
|
||||
ref.watch(authStateProvider.select((s) => s.user?.shopId));
|
||||
ref.watch(networkRecoveryCountProvider);
|
||||
try {
|
||||
final result = await _fetch();
|
||||
_cache = result;
|
||||
|
||||
@@ -4,6 +4,7 @@ import '../core/auth/auth_state.dart';
|
||||
import '../core/models/page_result.dart';
|
||||
import '../models/stock_in.dart';
|
||||
import '../repositories/stock_in_repository.dart';
|
||||
import 'connectivity_provider.dart';
|
||||
import 'inventory_provider.dart';
|
||||
|
||||
final stockInRepositoryProvider = Provider<StockInRepository>((ref) {
|
||||
@@ -25,6 +26,7 @@ class StockInListNotifier extends AsyncNotifier<PageResult<StockInOrder>> {
|
||||
@override
|
||||
Future<PageResult<StockInOrder>> build() async {
|
||||
ref.watch(authStateProvider.select((s) => s.user?.shopId));
|
||||
ref.watch(networkRecoveryCountProvider);
|
||||
try {
|
||||
final result = await _fetch();
|
||||
_cache = result;
|
||||
|
||||
@@ -4,6 +4,7 @@ import '../core/auth/auth_state.dart';
|
||||
import '../core/models/page_result.dart';
|
||||
import '../models/stock_out.dart';
|
||||
import '../repositories/stock_out_repository.dart';
|
||||
import 'connectivity_provider.dart';
|
||||
import 'inventory_provider.dart';
|
||||
|
||||
final stockOutRepositoryProvider = Provider<StockOutRepository>((ref) {
|
||||
@@ -25,6 +26,7 @@ class StockOutListNotifier extends AsyncNotifier<PageResult<StockOutOrder>> {
|
||||
@override
|
||||
Future<PageResult<StockOutOrder>> build() async {
|
||||
ref.watch(authStateProvider.select((s) => s.user?.shopId));
|
||||
ref.watch(networkRecoveryCountProvider);
|
||||
try {
|
||||
final result = await _fetch();
|
||||
_cache = result;
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
import '../core/api/api_client.dart';
|
||||
import '../core/auth/auth_state.dart';
|
||||
|
||||
typedef AuthLoginFn = Future<AuthUser> Function({
|
||||
required String shopCode,
|
||||
required String username,
|
||||
required String password,
|
||||
});
|
||||
|
||||
class AuthException implements Exception {
|
||||
final String message;
|
||||
const AuthException(this.message);
|
||||
@@ -10,6 +17,9 @@ class AuthException implements Exception {
|
||||
}
|
||||
|
||||
class AuthRepository {
|
||||
@visibleForTesting
|
||||
static AuthLoginFn? loginOverride;
|
||||
|
||||
/// POST /api/v1/auth/login
|
||||
/// Request: { shop_code, username, password }
|
||||
/// Response: { data: { access_token, refresh_token, expires_in, user: { id, username, real_name, role } } }
|
||||
@@ -18,6 +28,14 @@ class AuthRepository {
|
||||
required String username,
|
||||
required String password,
|
||||
}) async {
|
||||
final override = loginOverride;
|
||||
if (override != null) {
|
||||
return override(
|
||||
shopCode: shopCode,
|
||||
username: username,
|
||||
password: password,
|
||||
);
|
||||
}
|
||||
try {
|
||||
final resp = await PublicApiClient.post('/auth/login', data: {
|
||||
'shop_code': shopCode,
|
||||
|
||||
@@ -6,6 +6,7 @@ import 'package:go_router/go_router.dart';
|
||||
import '../../core/auth/auth_state.dart';
|
||||
import '../../core/theme/app_theme.dart';
|
||||
import '../../core/storage/login_history.dart';
|
||||
import '../../providers/connectivity_provider.dart';
|
||||
import '../../repositories/auth_repository.dart';
|
||||
|
||||
class LoginScreen extends ConsumerStatefulWidget {
|
||||
@@ -195,6 +196,14 @@ class _LoginScreenState extends ConsumerState<LoginScreen> {
|
||||
|
||||
Future<void> _login() async {
|
||||
if (!_formKey.currentState!.validate()) return;
|
||||
|
||||
// 登录前先检查连通性
|
||||
final isOnline = ref.read(connectivityProvider);
|
||||
if (!isOnline) {
|
||||
setState(() => _errorMessage = '服务器不可达,请检查网络连接后重试');
|
||||
return;
|
||||
}
|
||||
|
||||
setState(() {
|
||||
_loading = true;
|
||||
_errorMessage = null;
|
||||
@@ -382,6 +391,38 @@ class _LoginScreenState extends ConsumerState<LoginScreen> {
|
||||
onFieldSubmitted: (_) => _login(),
|
||||
),
|
||||
|
||||
// 离线提示(connectivityProvider 在 _AppBootstrap 中已预热)
|
||||
if (!ref.watch(connectivityProvider)) ...[
|
||||
const SizedBox(height: 12),
|
||||
Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 12, vertical: 10),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFFFFF8E1),
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
border: Border.all(
|
||||
color: const Color(0xFFF57F17)
|
||||
.withAlpha(120)),
|
||||
),
|
||||
child: const Row(
|
||||
children: [
|
||||
Icon(Icons.wifi_off,
|
||||
color: Color(0xFFF57F17), size: 16),
|
||||
SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'服务器不可达,请检查网络连接',
|
||||
style: TextStyle(
|
||||
color: Color(0xFF5D4037),
|
||||
fontSize: 13),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
|
||||
// Inline error
|
||||
if (_errorMessage != null) ...[
|
||||
const SizedBox(height: 12),
|
||||
|
||||
@@ -6,6 +6,7 @@ import '../../providers/finance_provider.dart';
|
||||
import '../../widgets/data_table_card.dart';
|
||||
import '../../widgets/multi_select_dropdown.dart' show ColDef, ColumnToggleButton, FilterableColumnHeader;
|
||||
import '../../widgets/page_scaffold.dart';
|
||||
import '../../providers/connectivity_provider.dart';
|
||||
|
||||
class FinanceScreen extends ConsumerWidget {
|
||||
const FinanceScreen({super.key});
|
||||
@@ -101,6 +102,9 @@ class _FinanceTabState extends ConsumerState<_FinanceTab> {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// 网络恢复时自动刷新
|
||||
ref.listen(networkRecoveryCountProvider, (_, __) => _refetch());
|
||||
|
||||
return FutureBuilder<List<FinanceRecord>>(
|
||||
future: _future,
|
||||
builder: (context, snap) {
|
||||
|
||||
@@ -5,6 +5,7 @@ import '../../models/inventory.dart';
|
||||
import '../../providers/inventory_provider.dart';
|
||||
import '../../widgets/data_table_card.dart';
|
||||
import '../../widgets/multi_select_dropdown.dart' show ColDef, ColumnToggleButton, FilterableColumnHeader;
|
||||
import '../../providers/connectivity_provider.dart';
|
||||
|
||||
class BatchTrackingScreen extends ConsumerStatefulWidget {
|
||||
const BatchTrackingScreen({super.key});
|
||||
@@ -77,6 +78,9 @@ class _BatchTrackingScreenState extends ConsumerState<BatchTrackingScreen> {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// 网络恢复时自动刷新
|
||||
ref.listen(networkRecoveryCountProvider, (_, __) => _refetch());
|
||||
|
||||
return FutureBuilder<List<ProductTrackingRecord>>(
|
||||
future: _future,
|
||||
builder: (context, snap) {
|
||||
|
||||
@@ -274,7 +274,7 @@ class _AppShellState extends ConsumerState<AppShell> {
|
||||
size: 16, color: Colors.white),
|
||||
SizedBox(width: 8),
|
||||
Text(
|
||||
'网络连接已断开 · 当前处于只读模式,所有写操作已禁用',
|
||||
'网络连接已断开 · 当前显示离线缓存数据,恢复后将自动刷新',
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 13,
|
||||
|
||||
Reference in New Issue
Block a user