flutter - Why can't I access the User's uid from the bloc's state in this example? - TagMerge
1Why can't I access the User's uid from the bloc's state in this example?Why can't I access the User's uid from the bloc's state in this example?

Why can't I access the User's uid from the bloc's state in this example?

Asked 1 years ago
0
1 answers

You can't access the 'uid' directly because 'activeUser' is a stream of 'user'. So you could wrap your Text-widget with a StreamBuilder and provide 'state.activeUser' as the stream:

StreamBuilder(
  stream: state.activeUser,
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return Text(snapshot.data?.uid : "");
    }
    return Text("");
  },
);

But I have a question there, why do you save the stream itself inside your UserState? Why not save only the User and emit a new state whenever authStateChanges fires? You could do something like this:

class UserBloc extends Bloc<UserEvent, UserState> {
  final AuthService  _authService;
  StreamSubscription<User?> _userSubscription;

  UserBloc(this._authService) : super(UserInitial()) {
    on<GetUser>(_getUser);
  }

  void _getUser(GetUser event, Emitter<UserState> emit) {
    _userSubscription ??= _authService.user.listen((user) {
      emit(UserLoaded(activeUser: user));
    });
  }
}

So you can change the UserState to hold a User? instead of a stream and you can access it directly inside you widget how you did it in your sample.

Attention: The code samples are only from my memory and probably wont work out of the box.

Source: link

Recent Questions on flutter

    Programming Languages