skip to Main Content

I have a bloc that keeps user data -via firebase- on the state. It works as it is but when the user signs out and sign in again, I can’t update the bloc with new user data.

Eg.

User_1 (name: one) signs out. Then User_2 (name: two) signs in. Bloc state still keeping data from User_1

user_state.dart

part of 'user_bloc.dart';

class UserState extends Equatable {
  const UserState();

  @override
  List<Object?> get props => [];
}

class UserLoading extends UserState {
  const UserLoading();

  @override
  List<Object> get props => [];
}

class UserLoaded extends UserState {
  final UserFindine user;

  UserLoaded({required this.user});

  @override
  List<Object> get props => [user];
}

user_event.dart

part of 'user_bloc.dart';

class UserEvent extends Equatable {
  const UserEvent();

  @override
  List<Object> get props => [];
}

class LoadUser extends UserEvent {
  const LoadUser();

  @override
  List<Object> get props => [];
}

class UpdateUser extends UserEvent {
  final UserFindine user;

  const UpdateUser(this.user);

  @override
  List<Object> get props => [user];
}

user_bloc.dart

class UserBloc extends Bloc<UserEvent, UserState> {
  final DatabaseRepository _databaseRepository;
  StreamSubscription? _databaseSubscription;

  UserBloc({
    required DatabaseRepository databaseRepository,
  })  : _databaseRepository = databaseRepository,
        super(UserLoading()) {
    on<LoadUser>((event, emit) {
      _databaseSubscription?.cancel();
      _databaseSubscription = _databaseRepository.getUser().listen((user) {
        add(UpdateUser(user));
      });
    });
    on<UpdateUser>((event, emit) {
      final data = event.user; // This data is right.
      emit(UserLoaded(user: data));
    });
  }
}

I’ve tried to trigger LoadUser event when the user signs in. But still getting old user data. Am I missing something?

Thanks for any help 🔥

Edit:

In my main.dart file:

MultiBlocProvider(
        providers: [
          BlocProvider<AuthBloc>(
            create: (context) => AuthBloc(
              authRepository: context.read<AuthRepository>(),
            ),
          ),
          BlocProvider(
            create: (_) => UserBloc(databaseRepository: DatabaseRepository())..add(LoadUser()),
          ),
        ],
),

Also I use this after sign in event.

UserBloc(databaseRepository: DatabaseRepository())..add(LoadUser());

2

Answers


  1. Just add emit(UserLoading()); above the line of final data = event.user;
    Because once UserLoaded state is emitted and again you want to emit the same state, it will not rebuild BlocBuilder so I prefer always emit two different states in one method.

    Login or Signup to reply.
  2. Similar happened to me when i had more than one instance of LoginBloc. In the case of normal pages, it’s useful to recreate the Bloc, but for the login, you do not want to have more than one instance of it or re-create it when you navigate.

    here is an example using AppRouter which contains a normal Bloc and a login Bloc, pls check the difference. i added some comments to the code.

    you might also try to put a breakpoint to the MultiblocProvider in your code to see if it’s called more than once.

    class AppRouter {
      late Repository repository;
      LoginCubit? loginCubit; //declare global login Bloc
    
      AppRouter() {
        repository = Repository(apiClient: ApiClient());
        loginCubit = LoginCubit(repository: repository); //create the Bloc once
      }
    
      Route? generateRoute(RouteSettings settings) {
        switch (settings.name) {
          case "/":
            return MaterialPageRoute(
              builder: (_) => BlocProvider.value( // use Blocprovider.value which will not create a new Bloc but use the one declared before
                value: loginCubit!,
                child: const LoginPage(key: null),
              ),
            );
          case "/main_page":
            final args = settings.arguments as Map;
            return MaterialPageRoute(
              builder: (_) => BlocProvider(
                create: (context) =>
                    OtherCubit( repository: repository),
                child: OtherPage(),
              ),
            );  
         }
       }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search