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

Rob Jones
May 5, 2020

--

Pulling down anywhere on the screen to call RefreshIndicator
Can pull down anywhere on screen

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 small Text 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:

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Rob Jones
Rob Jones

Written by Rob Jones

Programmer/Generalist/Intraday Algo Trader

No responses yet

Write a response