Reputation: 7064
I have added a setState
Method inside the build
widget after getting my data from API response via StreamBuilder. But it gives this error:
Unhandled Exception:
setState()
ormarkNeedsBuild()
called during build.
How do I avoid this situation?
My code:
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: StreamBuilder(
stream: bloc.getData,
builder: (context, AsyncSnapshot<Home> dataSnapshot) {
if (dataSnapshot.hasData) {
if (dataSnapshot.data.description != null) _expandHeightBy(40);
........
Function
_expandHeightBy(double increase) async {
setState(() {
_expandedHeightVal += increase;
});
}
Upvotes: 0
Views: 349
Reputation: 7064
Removed the setState
from the method calling as @CodePoet suggested and it actually worked fine.
_expandHeightBy(double increase) {
_expandedHeightVal += increase;
}
Upvotes: 0
Reputation: 1939
It is not possible to call setState during build, and for good reason. setState runs the build method. Therefore if you were able to call setState in build, it would infinitely loop the build method since it essentially calls itself.
Check out this article. It has an example of conditionally rendering based on a StreamBuilder. https://medium.com/@sidky/using-streambuilder-in-flutter-dcc2d89c2eae
Upvotes: 1