Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FLUTTER: How to use navigator in streambuilder?

I am trying to navigate inside a streambuilder but I have this error:"setState() or markNeedsBuild() called during build.". If I call navigate inside an onpressed button it works but not by just use it inside a condition. I am stuck. There is some code to show you.

Widget build(BuildContext context) {
    return Scaffold(
      body: StreamBuilder(
        stream:
            Firestore.instance.collection('rooms').document(pinid).snapshots(),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.hasData) {
            if ((snapshot.data['Votes'][0] + snapshot.data['Votes'][1]) >=
                snapshot.data['joueurs']) {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => Results(),
                  ));
            }
          }
          return Center(
            child: Text('VOUS AVEZ VOTE'),
          );
        },
      ),
    );
  }
like image 375
luc Avatar asked Jan 14 '20 17:01

luc


People also ask

How do I refresh my StreamBuilder flutter?

1 Answer. Declare a StreamController with broadcast , then set a friendly name to the Stream of this StreamController , then everytime you want to rebuild the wraped widget (the child of the StreamBuilder just use the sink property of the StreamController to add a new value that will trigger the StreamBuilder .


1 Answers

That's because Flutter is triggering a frame build when you are trying to navigate to another screen, thus, that's not possible.

You can schedule a post frame callback so you can navigate as soon as Flutter is done with tree rebuilding for that widget.

import 'package:flutter/foundation.dart';

  WidgetsBinding.instance.addPostFrameCallback(
     (_) => Navigator.push(context,
       MaterialPageRoute(
         builder: (context) => Results(),
       ),
     ),
   );
like image 179
Miguel Ruivo Avatar answered Sep 23 '22 06:09

Miguel Ruivo