Center Widget Vertically Inside A SingleChildScrollView


Answer :

ArtiomLK Suggested a solution in comments which helped me:

wrap SingleChildScrollView in a Center. The widgets tree is:

Center( child: SingleChildScrollView( child: Column(...)))

None of the others helped.


Solution:

Put your top level Stack inside Center widget.

body: Center(child: Stack(       children: _buildBody(),     ))); 

Tip to debug:

Use Flutter Inspector to find where the layout is going wrong.

I edited your code a bit(to make to work in my local) and then I inspected. It showed like below enter image description here We have a Stack and SingleChildScrollView as per code(refer right side of the diagram where the stack of widgets are displayed). As size is determined by SingleChildScrollView(contents inside it), Stack occupies only little space and by default, it aligned at top. So put it under Center, the whole Stack view will come in center.


There's a section about it in the official docs:

Using SingleChildScrollView with a Column

Source: https://api.flutter.dev/flutter/widgets/SingleChildScrollView-class.html

However I found that using a combination of the above worked better. Namely confining the Column to the minimum size possible (MainAxisSize.min). This should be fine, as the SingleChildScrollView will take up as much space as is possible on screen, before scrolling can happen.

Widget _buildPortraitPage() {     return Center(       child: SingleChildScrollView(         child: Column(           mainAxisSize: MainAxisSize.min, // <-- notice 'min' here. Important           children: [             Flexible(               child: Image.asset('assets/images/my-image.png'),             ),             Flexible(               child: Text('My content'),             ),           ],         ),       ),     );   } 

The layout engine in Flutter is pretty hard to figure out.


Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?