Stream builder is used to draw widget based on data from stream.

What is the right way to achieve navigation based on the data?

Details: There is a logout button in drawer. It clears the session and emits a data in the stream.

There's a stateless widget with stream builder listening on data and updating UI. How to make it navigate to login screen based on data in the stream?

2 Answers

0
mirkancal On

In your stateless widget's build method, you can listen changes in your stream with listen() method.

 Widget build(BuildContext context) {
    Repository.bulletins.listen((pet) {
      pet.documents[pet.documents.length - 1].data['animalType'] == "Dog"
          ? Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => LostPetForm(),
              ))
          : print('not yet');
    });
    return Scaffold(...
0
Harish Reddy On

Inspired from https://stackoverflow.com/a/54109955/1918649

In the build method of the widget that creates Profile

  @override
  Widget build(BuildContext context) {
    final userBloc = BlocProvider.of<UserBloc>(context);
    return ...
           somewhere here Profile(userBloc)
           ...
}

class Profile extends StatefulWidget  {

  final userBloc;

  Profile(this.userBloc);

  @override
  State<StatefulWidget> createState() => ProfileState();
}

class ProfileState extends State<Profile> {

  @override
  void initState() {
    super.initState();
    widget.userBloc.stream.listen((userData){
      if(userData==null) {
        Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => LandingPage(),
            ));
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        title: new Text("Profile"),
      ),
      drawer: CustomDrawer(),
      body: Center(
        child: StreamBuilder<UserModel>(
          initialData: widget.userBloc.user,
          stream: widget.userBloc.stream,
          builder: (ctx, snap) => snap.hasData?Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Image.network(snap.data?.imageUrl),
              Text(snap.data?.username)
            ],
          ):Text('You are logged out'),
        ),
      ),
    );
  }
}