admin管理员组文章数量:1122832
I have a problem with my authentication service using AutoRoute and GetIt. The problem is that when I am in CreateAccountScreen and I am logged in, the counter starts counting. When the counter ends, the router sends me to the login screen, all good, but when I logged in for the second time, the counter ends and the router does not redirect me like the first time. How can I verify all the time that the router redirects me every time the counter ends?
This is my main.dart
import 'package:auto_rutas_prueba_auth/app/app.dart';
import 'package:auto_rutas_prueba_auth/bootstrap.dart';
void main() {
bootstrap(App.new);
}
This is my get_it.dart
import 'package:get_it/get_it.dart';
GetIt _getIt = GetIt.instance;
GetIt get getIt => _getIt;
The bootstrap function
Future<void> bootstrap(FutureOr<Widget> Function() builder) async {
FlutterError.onError = (details) {
log(details.exceptionAsString(), stackTrace: details.stack);
};
Bloc.observer = const AppBlocObserver();
// Add cross-flavor configuration here
WidgetsFlutterBinding.ensureInitialized();
getIt..registerSingleton<AuthProvider>(AuthProvider())
..registerSingleton<AuthGuard>(AuthGuard())
..registerSingleton<AppRouter>(AppRouter());
runApp(await builder());
}
The app.dart
import 'package:auto_rutas_prueba_auth/get_it.dart';
import 'package:auto_rutas_prueba_auth/l10n/l10n.dart';
import 'package:flutter/material.dart';
class App extends StatelessWidget {
App({super.key});
// final routerConfig = getIt<RouterConfig<UrlState>>();
final appRouter = getIt<AppRouter>();
final authProvider = getIt<AuthProvider>();
@override
Widget build(BuildContext context) {
return MaterialApp.router(
theme: ThemeData(
appBarTheme: AppBarTheme(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
),
useMaterial3: true,
),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
// routerConfig: routerConfig,
routerConfig: appRouter.config(
reevaluateListenable: authProvider,
),
);
}
}
And the router
import 'dart:async';
import 'package:auto_route/auto_route.dart';
import 'package:auto_rutas_prueba_auth/app/router/router.gr.dart';
import 'package:auto_rutas_prueba_auth/get_it.dart';
import 'package:flutter/cupertino.dart';
import 'package:logger/logger.dart';
@AutoRouterConfig()
class AppRouter extends RootStackRouter {
@override
List<AutoRoute> get routes => [
AutoRoute(
page: CreateAccountRoute.page,
initial: true,
),
AutoRoute(
page: LoginRoute.page,
path: '/login',
),
AutoRoute(
page: ProfileRoute.page,
path: '/profile',
guards: [getIt<AuthGuard>()],
),
AutoRoute(
page: MainRoute.page,
path: '/home',
guards: [getIt<AuthGuard>()],
),
];
}
class AuthGuard extends AutoRouteGuard {
@override
void onNavigation(NavigationResolver resolver, StackRouter router) {
if (getIt<AuthProvider>().isLoggedIn) {
resolver.next();
} else {
resolver.redirect(const LoginRoute(), replace: true);
}
}
}
class AuthProvider extends ChangeNotifier {
bool _isLoggedIn = false;
final Logger _logger = Logger();
Timer? _timer;
bool get isLoggedIn => _isLoggedIn;
void login() {
_isLoggedIn = true;
notifyListeners();
_startSession();
}
void _startSession() {
_timer?.cancel();
var secondsRemaining = 5;
_logger.f('Sesión activa por $secondsRemaining segundos.');
_timer = Timer.periodic(const Duration(seconds: 1), (timer) {
secondsRemaining--;
_logger.i('$secondsRemaining segundos restantes.');
if (secondsRemaining <= 0) {
logout();
timer.cancel();
}
});
}
void logout() {
_isLoggedIn = false;
notifyListeners();
}
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
}
My create account screen
import 'package:auto_route/auto_route.dart';
import 'package:auto_rutas_prueba_auth/app/router/router.dart';
import 'package:auto_rutas_prueba_auth/app/router/router.gr.dart';
import 'package:auto_rutas_prueba_auth/get_it.dart';
import 'package:flutter/material.dart';
@RoutePage()
class CreateAccountScreen extends StatelessWidget {
const CreateAccountScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('CreateAccount Screen'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
getIt<AuthProvider>().login();
context.router.replace(
const MainRoute(),
);
},
// onPressed: () => context.router.replace(const MainRoute()),
child: const Text('Iniciar Sesión'),
),
),
);
}
}
My login screen
import 'package:auto_route/auto_route.dart';
import 'package:auto_rutas_prueba_auth/app/router/router.dart';
import 'package:auto_rutas_prueba_auth/app/router/router.gr.dart';
import 'package:auto_rutas_prueba_auth/get_it.dart';
import 'package:flutter/material.dart';
@RoutePage()
class LoginScreen extends StatelessWidget {
const LoginScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Login Screen'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
getIt<AuthProvider>().login();
context.router.replace(
const MainRoute(),
);
},
child: const Text('Login'),
),
),
);
}
}
本文标签: flutterAutoRoute AuthenticationStack Overflow
版权声明:本文标题:flutter - AutoRoute Authentication - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736301270a1931120.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论