I have written some simplified code where I want the condition of firestore data to be able to update a parent widget.
I get the error: setState() or markNeedsBuild() called during build.
How can I update the state of myVar from inside StreamBuilder? After updating myVar the StreamBuilder will not be accessed, instead only the text Waiting... should be displayed.
Edit: I updated myVar to be used as the document ID of Firestore. To clarify, I want to be able to update the document of the StreamBuilder from inside the StreamBuilder. In other words as the question says, update stateful widget from child StreamBuilder.
class MyWidget extends StatefulWidget {
MyWidget({Key key})
: super(key: key);
@override
_MyWidgetState createState() {
return _MyWidgetState();
}
}
class _MyWidgetState extends State<MyWidget> {
String myVar = "someID";
@override
Widget build(BuildContext context) {
if (myVar == null) {
// update myVar async, so that StreamBuilder will be re-rendered
asyncFunctUpdate(myVar); // edit: finally got it to work if doing setState from asyncFuncUpdate(myvar).then(()=>setState)
return Text("Waiting...");
}
else
return StreamBuilder<DocumentSnapshot>(
stream: Firestore.instance
.collection('myCollection')
.document(myVar)
.snapshots(),
builder: (context, orderSnapshot) {
if (!orderSnapshot.data.exists)
setState(() {
myVar = null;
});
else return Text(orderSnapshot);
});
}
}
Workaround: In my case it was simpler to just return buttons from the StreamBuilder and setState as normally from onPressed functions.
Solution: Instead of doing setState from an async function do it within the .then clause (see code above)
asyncmethod and call it from stream builder. Something like:void setMyVar(String var) async { setState(() { myVar = var}). This should run after the build is done. - danypatabuildcompletes. As for the actual solution, check Artem's answer. - Ovidiu