Farwa
Farwa

Reputation: 7064

Flutter - How to dynamically add height value of a container before loading the UI?

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() or markNeedsBuild() 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

Answers (2)

Farwa
Farwa

Reputation: 7064

Removed the setState from the method calling as @CodePoet suggested and it actually worked fine.

     _expandHeightBy(double increase) {
       _expandedHeightVal += increase;
     }

Upvotes: 0

Benedikt J Schlegel
Benedikt J Schlegel

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

Related Questions