Flutter Quick Tip— Centering a Widget in a SingleChildScrollView with RefreshIndicator

This is a quick post about being able to center a widget vertically/horizontally in a SingleChildScrollView
while being able to pull-down anywhere on the screen to use the RefreshIndicator
.
- I needed a scrollable field in order to use
RefreshIndicator
- I needed to center my text within that scrollable field. Centering it horizontally was easy — centering it vertically (i.e., center of the screen) was not so easy.
- I wanted to pull down on the screen anywhere to initiate the
RefreshIndicator
call, not just on the smallText
widget itself.
For this example, I just modified the basic, boilerplate Flutter code you get when you start a new project. When you pull down to refresh, the _counter
increases by one and the text on the screen is updated by setState
to show the update.
Here is the build
method:
Widget build(BuildContext context) {
return Scaffold(
body: RefreshIndicator(
onRefresh: _refreshPage,
child: SingleChildScrollView(
physics: AlwaysScrollableScrollPhysics(),
child: Container(
alignment: Alignment.center,
height: MediaQuery.of(context).size.height,
child: Text('$_counter', style: TextStyle(fontSize: 30)),
),
),
)
);
}
The AlwaysScrollableScrollPhysics
allows for the pull-down RefreshIndicator
no matter the length.
The Container
sets the alignment in the center. The MediaQuery.of(context).size.height
gets the height of the screen for the center alignment.
Now, you can pull-down anywhere on the screen and RefreshIndicator
will be called.
Edit 05/15/20: For those of you wondering about offsetting the AppBar height, you can do the following in the Container
:
height: MediaQuery.of(context).size.height - MediaQuery.of(context).padding.top
Full code: