Body size & margins not being respected inside NestedScrollView

Viewed 876

I'm trying to understand why on the code bellow "Containers" in this case as an example, fills in the entire space, even though the have constraints or sizes.

return Scaffold(
      
      body: SafeArea(
        child: NestedScrollView(
          physics: BouncingScrollPhysics(),
          headerSliverBuilder: (context, innerBoxIsScrolled) {
            return <Widget>[];
          },
          body: Container(
            constraints: BoxConstraints(
              maxHeight: 100,
              minWidth: 100,
            ),
            color: Colors.red,
            height: 100,
            width: 100,
            child: Container(
              constraints: BoxConstraints(
                maxHeight: 50,
                minWidth: 50,
              ),
              color: Colors.yellow,
              height: 50,
              width: 50,
              child: Text('a'),
            ),
          ),
        ),
      ),
    );
3 Answers

You can add a Column over the entire page to control the size of each Container

You can try this:

 return Scaffold(

  body: SafeArea(
    child: NestedScrollView(
      physics: BouncingScrollPhysics(),
      headerSliverBuilder: (context, innerBoxIsScrolled) {
        return <Widget>[];
      },
      body: Column(
        children: [
          Container(

            color: Colors.red,
            height: 100,
            width: 100,
            child: Container(
              
              margin: EdgeInsets.all(25.0),
              color: Colors.yellow,
              height: 50,
              width: 50,
              child: Text('a'),
            ),
          ),
        ],
      ),
    ),
  ),
);

If a child wants a different size from its parent and the parent doesn’t have enough information to align it, then the child’s size might be ignored. Be specific when defining alignment.

Here you have first Container wanting to have its size but they are ignored because screen forces it to be exactly the same size as the screen minus SliverAppBars that you might pass to headerSliverBuilder.

In order to Container retain its size, set parent, that will have its own constrains e.g. Center, Column, Stack etc

Chnage NestedScrollView to CustomScrollView and move your Widget list to slivers attribute.

CustomScrollView won't add additional padding to the height.

SafeArea(
   child: CustomScrollView(
       slivers: <Widget>[
          getCatalogueAppbar(size, context),
          SliverToBoxAdapter(
            child: Container(
              width: size.width,
              child: buildTabBarView(size),
            ),
          ),
        ]));
Related