4

When start the app, first work AuthCubit

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
      providers: [
        BlocProvider<AuthCubit>(
            create: (context) => getIt<AuthCubit>()..startApp()),
        BlocProvider<CheckRoleCubit>(
            create: (context) => getIt<CheckRoleCubit>()),
      ],
      child: MaterialApp(
        home: InitialScreen(),
      ),
    );
  }
}

which use the simple functions:

void startApp() async {
    emit(AuthState.splashScreen());
    await Future.delayed(Duration(seconds: 2));
    checkAuthRequest();
  }

  Future<void> checkAuthRequest() async {
    final userOption = await firebaseAuthRepository.getUser();
    emit(
      userOption.fold(
        () => AuthState.unauthenticated(),
        (_) => AuthState.authenticated(),
      ),
    );
  } 

in InitialScreen I am using BlocConsumer:

 return BlocConsumer<AuthCubit, AuthState>(
      listener: (context, state) {
        state.maybeMap(
          orElse: () {},
          authenticated: (_) {
            context.read<CheckRoleCubit>().checkRole();
          },
        );
      },
      builder: (context, state) {
        return state.maybeMap(
          authenticated: (_) => CheckRole(),
          unauthenticated: (_) => HomeScreen(),
          orElse: () => Container(),
        );
      },
    );

in CheckRoleScreen:

 return BlocBuilder<CheckRoleCubit, CheckRoleState>(
      builder: (context, state) {
        return state.map(
          initial: (_) => Container(color: Colors.amberAccent),
          admin: (_) => Admin(),
          user: (_) => HomeScreen(),
          loadFailure: (_) => Container(),
        );
      },
    );

in CheckRoleCubit I am creating a simple function, which fetch userData from Firestore.

StreamSubscription userDataStreamSubscription;
  Future<void> checkRole() async {
    userDataStreamSubscription = userDataRepository.fetchUserData().listen(
      (failureOrFetch) {
        emit(
          failureOrFetch.fold(
            (failure) => CheckRoleState.loadFailure(failure),
            (userData) {
              if (userData.role == 'admin') {
                return CheckRoleState.admin();
              } else {
                return CheckRoleState.user();
              }
            },
          ),
        );
      },
    );
  } 

Issue is when I am open the app or use restart, after splashScreen, emit initial state of CheckRoleCubit and display container for a second and then display homeScreen or adminScreen. What I am doing wrong?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Andrey Khan
  • 183
  • 1
  • 3
  • 13

0 Answers0