fix: 增加路由守卫(token 失效自动回登录页)
401 登出后当前页面不跳转,导致主框架停留在异常状态 (如会员状态一直加载);守卫在认证态变化时导航到 /login 或 /home Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import 'core/auth/auth_provider.dart';
|
||||
import 'features/auth/login_page.dart';
|
||||
import 'features/cps/cps_product_list_page.dart';
|
||||
import 'features/cps/cps_provider.dart';
|
||||
@@ -28,6 +29,22 @@ class SloganApp extends ConsumerWidget {
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final router = ref.watch(routerProvider);
|
||||
final auth = ref.watch(authProvider);
|
||||
// 路由守卫:token 失效/登出 → 回登录页;token 有效且在登录页 → 进主框架
|
||||
final path =
|
||||
router.routerDelegate.currentConfiguration.uri.path;
|
||||
final authed = auth.value?.authenticated ?? false;
|
||||
if (!auth.isLoading) {
|
||||
if (!authed && path != '/login') {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (context.mounted) router.go('/login');
|
||||
});
|
||||
} else if (authed && path == '/login') {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (context.mounted) router.go('/home');
|
||||
});
|
||||
}
|
||||
}
|
||||
return MaterialApp.router(
|
||||
title: '我的形象穿搭',
|
||||
theme: ThemeData(
|
||||
|
||||
Reference in New Issue
Block a user