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