简体   繁体   中英

How to navigate in flutter with bloc

I have a login/signup page. When a user sign up, I call my bloc code and do firebase signup. Now when I complete the signup I want the app to be redirected to the home page. How can I can I control the navigation flow from the bloc?

I tried using firebase authstatechanges stream in the 'home' of material app but that only works when the app first starts. It does not work after I have already loaded the signup page.

Also I created a method just to listen to the stream boolean value that gets changed when the user is signed up but that method is not receiving any updates.

class EventsBloc{

    final FirebaseAuth firebaseAuth = FirebaseAuth.instance;

    Sink<User> get doSignup => _signupController.sink;

    final _signupController = StreamController<User>();

    Stream<bool> get isLoading => _isLoadingSubject.stream;

    final _isLoadingSubject = BehaviorSubject<bool>(seedValue: false);



    EventsBloc()
    {
      _signupController.stream.listen((user){

        _isLoadingSubject.add(true);
        firebaseAuth.createUserWithEmailAndPassword(email: user.email, password: user.password).then((firebaseUser) {

          _isLoadingSubject.add(false);
           // I WANT TO NAVIGATE TO THE HOME PAGE HERE
          Firestore.instance.collection('user').document()
              .setData({ 'email': user.email, 'phone': user.phoneNumber, 'name': user.name });


        });

      });
    }


  }

I think the auth state stream in a parent StreamBuilder should work? That would be the nicest way in my opinion.

An option is to add a new stream to your bloc, like Stream<String> get doNavigate , and add events to it when you want the widget to navigate somewhere. You can think of navigation actions as just another output stream from your bloc.

Yet another option is to expand the scope of isLoading to include information like login status too. You could have an enum with all possible statuses like:

enum Status { signedOut, loading, signedIn }

And then expose it from your bloc instead of just the loading state:

class EventBloc {
  // ...
  Stream<Status> get status => _statusSubject.stream;
  final _statusSubject = BehaviorSubject<Status>(seedValue: Status.signedOut);

  EventsBloc() {
    _signupController.stream.listen((user) async {
      _statusSubject.add(Status.loading);
      final firebaseUser = await firebaseAuth.createUserWithEmailAndPassword(
        email: user.email,
        password: user.password,
      );
      Firestore.instance.collection('user').document().setData(
          {'email': user.email, 'phone': user.phoneNumber, 'name': user.name});
      _statusSubject.add(Status.signedIn);
    });
  }
}```

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM