0

Estoy utilizando riverpod como gestor de estados y go_router para la administración de rutas. En este punto tengo inconvenientes al declarar las redirecciones de las rutas dependiendo el estado de la autenticación, es decir: quiero que si el usuario NO está autenticado pueda acceder a todas las rutas excepto a una '/product/', y si SÍ está autenticado pueda acceder a todas. El problema que presento es que al estar en la pantalla de login y colocar las credenciales correctas no me redirige a la página del home, sino que se queda en el login.

Comparto el código para ser más específico.

import 'package:app_flutter_imm/presentation/providers/auth_provider/auth_provider.dart';
import 'package:app_flutter_imm/presentation/screens/instructivo_all_screen.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';

import '../../presentation/screens/screens.dart';
import 'app_router_notifier.dart';

final goRouterProvider = Provider((ref) {

  final goRouterNotifier = ref.read(goRouterNotifierProvider);
  return GoRouter(
    initialLocation: '/checking',
    refreshListenable: goRouterNotifier,
    routes: [
      GoRoute(
          path: '/',
          name: HomeScreen.name,
          builder: (context, state) => const HomeScreen(),
          routes: [
            GoRoute(
              path: 'speciality/:id',
              name: SpecialityScreen.name,
              builder: (context, state) {
                final specialId = state.pathParameters['id'] ?? 'no-id';
                return SpecialityScreen(specialId: specialId);
              },
            ),
            GoRoute(
              path: 'posts/:id',
              name: PostScreen.name,
              builder: (context, state) {
                final postId = state.pathParameters['id'] ?? 'no-id';
                return PostScreen(postId: postId);
              },
            ),
            GoRoute(
              path: 'services/:id',
              name: ServicesScreen.name,
              builder: (context, state) {
                final serviceId = state.pathParameters['id'] ?? 'no-id';
                return ServicesScreen(serviceId: serviceId);
              },
            ),
            GoRoute(
              path: 'product/:id',
              name: ProductScreen.name,
              builder: (context, state) {
                final productId = state.pathParameters['id'] ?? 'no-id';
                return ProductScreen(productId: productId);
              },
            ),
            GoRoute(
              path: 'doctorgineco/:id',
              name: DoctorGinecoDetailScreen.name,
              builder: (context, state) {
                final doctorId = state.pathParameters['id'] ?? 'no-id';
                return DoctorGinecoDetailScreen(doctorId: doctorId);
              },
            ),
            GoRoute(
              path: 'doctorendo/:id',
              name: DoctorEndoDetailScreen.name,
              builder: (context, state) {
                final doctorId = state.pathParameters['id'] ?? 'no-id';
                return DoctorEndoDetailScreen(doctorId: doctorId);
              },
            ),
            GoRoute(
              path: 'instructivo/:id',
              name: InstructivoDetailScreen.name,
              builder: (context, state) {
                final instructiveId = state.pathParameters['id'] ?? 'no-id';
                return InstructivoDetailScreen(instructiveId: instructiveId);
              },
            ),
          ]),
      GoRoute(
        path: '/checking',
        name: CheckAuthStatusScreen.name,
        builder: (context, state) => const CheckAuthStatusScreen(),
      ),
      GoRoute(
        path: '/postsAll',
        name: PostAllScreen.name,
        builder: (context, state) => const PostAllScreen(
          post: [],
        ),
      ),
      GoRoute(
        path: '/docginecolist',
        name: DoctorsGinecoScreen.name,
        builder: (context, state) => const DoctorsGinecoScreen(
          docgineco: [],
        ),
      ),
      GoRoute(
        path: '/docendolist',
        name: DoctorsEndoScreen.name,
        builder: (context, state) => const DoctorsEndoScreen(
          docendo: [],
        ),
      ),
      GoRoute(
        path: '/servicesAll',
        name: ServicesAllScreen.name,
        builder: (context, state) => const ServicesAllScreen(
          service: [],
        ),
      ),

      GoRoute(
        path: '/productsAll',
        name: ProductsAllScreen.name,
        builder: (context, state) => const ProductsAllScreen(
          producto: [],
        ),
      ),

      GoRoute(
        path: '/instructivoAll',
        name: InstructivoAllScreen.name,
        builder: (context, state) => const InstructivoAllScreen(
          instructi: [],
        ),
      ),

      GoRoute(
        path: '/contact',
        name: ContactScreen.name,
        builder: (context, state) => const ContactScreen(),
      ),

      GoRoute(
        path: '/loginScreen',
        name: LoginScreen.name,
        builder: (context, state) => const LoginScreen(),
      ),
    ],

    redirect: (contex, state) {

      final isGoingTo = state.matchedLocation;
      final authStatus = goRouterNotifier.authStatus;

      if (isGoingTo == '/checking' && authStatus == AuthStatus.checking) return null;

      if (authStatus == AuthStatus.notAuthenticated) {
        if (
          isGoingTo == '/' ||
          isGoingTo == '/loginScreen' ||
          isGoingTo == '/postsAll' ||
          isGoingTo == '/docginecolist' ||
          isGoingTo == '/docendolist' ||
          isGoingTo == '/servicesAll' ||
          isGoingTo == '/productsAll' ||
          isGoingTo == '/instructivoAll' ||
          isGoingTo.contains('/posts/')  ||
          isGoingTo.contains('/speciality/')  ||
          isGoingTo.contains('/services/')  ||
         // isGoingTo.contains('/product/')  ||
          isGoingTo.contains('/doctorgineco/')  ||
          isGoingTo.contains('/doctorendo/')  ||
          isGoingTo.contains('/instructivo/')  ||
          isGoingTo == '/contact' ) return null;

        return '/loginScreen';
      }

      if (authStatus == AuthStatus.authenticated) {
        if (isGoingTo == '/loginScreen' || isGoingTo == '/checking') return '/';
    return null;
        
      }
        return '/';

    }
  );
});

Código del appNotifier

import 'package:app_flutter_imm/presentation/providers/auth_provider/auth_provider.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';


final goRouterNotifierProvider = Provider((ref) {
  final authNotifier = ref.read( authProvider.notifier);
  return GoRouterNotifier(authNotifier);
});


class GoRouterNotifier extends ChangeNotifier {

  final AuthNotifier _authNotifier;

  AuthStatus _authStatus = AuthStatus.checking;

  GoRouterNotifier(this._authNotifier) {
    _authNotifier.addListener((state) {
      authStatus = state.authStatus;
    });
  }


  AuthStatus get authStatus => _authStatus;

  set authStatus( AuthStatus value ) {
    _authStatus = value;
    notifyListeners();
  }

}

Código del auth_provider (riverpod)

import 'package:app_flutter_imm/infrastructure/errors/auth_errors.dart';
import 'package:app_flutter_imm/infrastructure/repositories/auth_repository_impl.dart';
import 'package:app_flutter_imm/infrastructure/services/key_value_storage_service.dart';
import 'package:app_flutter_imm/infrastructure/services/key_value_storage_service_impl.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../domain/entities/user_entities.dart';
import '../../../domain/repositories/auth_repository.dart';


final authProvider = StateNotifierProvider<AuthNotifier,AuthState>((ref) {

  final authRepository = AuthRepositoryImpl();
  final keyValueStorageService = KeyValueStorageServicesImple();

  return AuthNotifier(
    authRepository: authRepository,
    keyValueStorageService: keyValueStorageService
  );
});


class AuthNotifier extends StateNotifier<AuthState> {

  final AuthRepository authRepository;
  final KeyValueStorageServices keyValueStorageService;

  AuthNotifier({
    required this.authRepository,
    required this.keyValueStorageService,
  }): super( AuthState() ) { 
    checkAuthStatus();
   }
  

  Future<void> loginUser( String email, String password ) async {
    await Future.delayed(const Duration(milliseconds: 500));

    try {
      final user = await authRepository.login(email, password);
      _setLoggedUser( user );

    } on CustomError catch (e) {
      logout( e.message );
    } catch (e){
      logout( 'Error no controlado' );
    }

  }

  void checkAuthStatus() async {
    final token = await keyValueStorageService.getValue<String>('token');
    if( token == null ) return logout();

    try {
      final user = await authRepository.checkAuthStatus(token);
      _setLoggedUser(user);

    } catch (e) {
      logout();
    }

  }

  void _setLoggedUser( User user ) async {
    
    await keyValueStorageService.setKeyValue('token', user.token);

    state = state.copyWith(
      user: user,
      authStatus: AuthStatus.authenticated,
      errorMessage: '',
    );
  }

  Future<void> logout([ String? errorMessage ]) async {
    
    await keyValueStorageService.removeKey('token');

    state = state.copyWith(
      authStatus: AuthStatus.notAuthenticated,
      user: null,
      errorMessage: errorMessage
    );
  }

}



enum AuthStatus { checking, authenticated, notAuthenticated }

class AuthState {

  final AuthStatus authStatus;
  final User? user;
  final String errorMessage;

  AuthState({
    this.authStatus = AuthStatus.checking, 
    this.user, 
    this.errorMessage = ''
  });

  AuthState copyWith({
    AuthStatus? authStatus,
    User? user,
    String? errorMessage,
  }) => AuthState(
    authStatus: authStatus ?? this.authStatus,
    user: user ?? this.user,
    errorMessage: errorMessage ?? this.errorMessage
  );

} 

Código del loginScreen

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:app_flutter_imm/presentation/providers/auth_provider/auth_provider.dart';
import 'package:app_flutter_imm/presentation/providers/login_provider/login_form_provider.dart';
import 'package:app_flutter_imm/presentation/widgets/widgets.dart';

class LoginScreen extends StatelessWidget {
  static const String name = 'loginScreen';
  const LoginScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Color(0xFFF8F7F7),
        title: const Text('Inciar Seción')),
      body: const _LoginView(),
    );
  }
}

class _LoginView extends StatelessWidget {
  const _LoginView();

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
      child: const Scaffold(
        backgroundColor: Color(0xFFF8F7F7),
        body: Padding(
          padding: EdgeInsets.all(8.0),
          child: SingleChildScrollView(
            child: Column(
              children: [
                FlutterLogo(size: 100),
                _LoginForm(),
                SizedBox(height: 20)
              ],
            ),
          ),
        ),
      ),
    );
  }
}

class _LoginForm extends ConsumerWidget {
  const _LoginForm();

   void showSnackbar( BuildContext context, String message ) {
    ScaffoldMessenger.of(context).hideCurrentSnackBar();
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message))
    );
    }  

  @override
  Widget build(BuildContext context, WidgetRef ref) {

    final loginForm = ref.watch(loginFormProvider);

    ref.listen(authProvider, (previous, next) {
      if ( next.errorMessage.isEmpty) return;
      showSnackbar( context, next.errorMessage);
     });


    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 30),
      child: Column(
        children: [
     
          const SizedBox( height: 90 ),

           CustomTextFormField(
            label: 'Correo',
            keyboardType: TextInputType.emailAddress,
            onChanged: ref.read(loginFormProvider.notifier).onEmailChange,
            errorMessage: loginForm.isFormPosted ?
               loginForm.email.errorMessage 
               : null,
          ),
          const SizedBox( height: 30 ),

          CustomTextFormField(
            label: 'Contraseña',
            obscureText: true,
            onChanged: ref.read(loginFormProvider.notifier).onPasswordChanged,
            onFieldSubmitted: (_) => ref.read(loginFormProvider.notifier).onFormSubmit(),
            errorMessage: loginForm.isFormPosted ?
               loginForm.password.errorMessage 
               : null,
          ),
    
          const SizedBox( height: 30 ),

           SizedBox(
            width: double.infinity,
            height: 50,
            child: FilledButton.tonalIcon(
            onPressed: () {
              ref.read(loginFormProvider.notifier).onFormSubmit();
             },
            icon: const Icon(Icons.login_sharp),
            label: const Text('Ingresar'),
          ),
          ),

      
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Text('¿No tienes cuenta?'),
              TextButton(
                onPressed: ()=> context.push('/'), 
                child: const Text('Contactanos')
              )
            ],
          ),

   
        ],
      ),
    );
  }
  
  }
2
  • Añade el código de la pantalla de inicio de sesión, para verificar como estas ingresando, además si te sale algún error también agrégalo.
    – Alex
    Commented el 21 oct. 2023 a las 16:47
  • Ok, ya agregue el codigo del loginScreen a la pregunta, en realidad no percibo ningún error. pero te comento que si el "initialLocation" es /loginScreen si funciona la redirección de la ruta al home, pero no es lo que requiero, ya que necesito que sea el home la primera pantalla. muchas gracias
    – Loyal
    Commented el 23 oct. 2023 a las 14:11

1 respuesta 1

0

Esto se debe a como usas el provider de riverpod: tú usas ref.read(goRouterNotifierProvider);, deberías usar ref.watch para que go router esté escuchando los cambios de tu AuthState y con base a ese estado lo redirija a la ruta pertinente. En general solo sería que arregles eso en el changeNotifier que creaste y donde llamas a ref.read(goRouterNotifierProvider);

Ese código se puede mejorar mucho y hacer más mantenible.

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.