Displaying a progress indicator

Especially in app development, you’re often faced with asynchronous operations. That’s because the UI thread must not be blocked since at any time the user should be able to interact with the app and that requires drawing on the screen, which happens in the UI thread.

If there’s anything the user has to wait for, we still want to indicate this circumstance. That’s what progress indicators are for.

Ideally, the progress indicator is shown on top of everything, preventing the user from interacting with the UI.

If you’re just here to see the results or copy off the code, just click one of the buttons:

Let’s build a progress indicator that looks like this:

A black with white text progress indicator above an overlay
A progress indicator above an overlay

What does Flutter provide?

Flutter already provides us two progress indicators as material widgets: the LinearProgressIndicator and the CircularProgressIndicator and this is awesome! Since they are nothing else but Widgets, we can use them just like that:

Container(
  child: CircularProgressIndicator(),
  width: 32,
  height: 32
);

That would give us something like this:

The circular progess indicator provided by Flutter
The provided progress indicator (circle)

A little bit of text for a descriptive progress indicator

Now what we want is to display a context so that the user knows, what he is actually waiting for. So let’s add some descriptive text and put everything in a container to make it stand out from the rest of the widget.

Container(
    padding: EdgeInsets.all(16),
    color: Colors.black.withOpacity(0.8),
    child: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      mainAxisSize: MainAxisSize.min,
      children: [
        _getLoadingIndicator(),
        _getHeading(),
        _getText('Text')
      ]
  )
)

Widget _getLoadingIndicator() {
  return Padding(
    child: Container(
        child: CircularProgressIndicator(
            strokeWidth: 3
        ),
        width: 32,
        height: 32
    ),
    padding: EdgeInsets.only(bottom: 16)
  );
}

Widget _getHeading() {
  return Padding(
    child: Text(
      'Please wait …',
      style: TextStyle(
        color: Colors.white,
        fontSize: 16
      ),
      textAlign: TextAlign.center,
    ),
    padding: EdgeInsets.only(bottom: 4)
  );
}

Widget _getText(String displayedText) {
  return Text(
    displayedText,
    style: TextStyle(
        color: Colors.white,
        fontSize: 14
    ),
    textAlign: TextAlign.center,
  );
}

That looks like a lot of change but essentially what I’ve done is wrapping everything in a Container widget, giving it a semi-transparent background color and some padding. Then, I want the indicator we built above, some generic text (“Please wait …”) and a little more detailed explanation on what is done.

Since we have three widgets among themselves, I decided to use a Column widget and put the three just mentioned components in there. To keep it readable, I outsourced every component in a separate method.

Now, what we have is something like that:

A circular progress indicator with text
A circular progress indicator with some text

Looks kind of what we want to achieve. But before we refine the visuals, let’s think about how we want to display it. I said I would want to display this on top of everything. After all, that would mean nothing more than a Stack widget with the loading indicator as the last child element. But what be the consequences for a project with more than one route? Every route would need to have a Stack widget in its root with the LoadingIndicator in it and a variable storing whether to display it.

Another approach could be to have a root Widget that has this kind of structure and then every route widget as a child of that. One could then use InheritedWidget or provider to make this controllable from every child widget.

Still, this does not feel like the best approach to me. There is something else we can do: the material package already gives us the possibility to show a dialog.
The great thing about it: this brings many options we need anyways:

  • An overlay that puts the attention to the progress indicator
  • The parameter barrierDismissible that prevents the user from dismissing the dialog by tapping the overlay background
  • shape parameter that enables us to enclose the dialog in a container with rounded corners

Let’s first wrap the code we’ve written so far in a separate file and a StatelessWidget called LoadingIndicator. I’ve already done this and uploaded a gist.

Using showDialog() and AlertDialog widget

Now, how do show that dialog? Let’s try it with this piece of code:

void showLoadingIndicator([String text]) {
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        content: LoadingIndicator(
          text: text
        ),
      );
    },
  );
}

The showDialog has two mandatory arguments: context (referring to a BuildContext) and builder which is nothing else than a function with a BuildContext as its only argument.
In the builder function we return an AlertDialog. The only content is the LoadingIndicator we just implemented.

Progress indicator with text using showDialog
Loading indicator with text using showDialog

We’re getting nearer to the desired result. But there are still some caveats:

  • There is a border around the LoadingIndicator
  • The user can dismiss the dialog by tapping anywhere on the background
  • The (Android) user can dismiss the dialog by using the hardware back button of his phone
  • The dialog does not have round corners

This is how we can fix the mentioned issues:

void showLoadingIndicator([String text]) {
  showDialog(
    context: context,
    barrierDismissible: false,
    builder: (BuildContext context) {
      return WillPopScope(
        onWillPop: () async => false,
        child: AlertDialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(8.0))
          ),
          backgroundColor: Colors.black87,
          content: LoadingIndicator(
            text: text
          ),
        )
      );
    },
  );
}

Let me explain what this codes snippet does:

  • In order to get rid of the border, I the set backgroundColor of the AlertDialog which is the same color as the LoadingIndicator
  • Round corners are achieved by assigning RoundedRectangleBorder to the shape argument of the AlertDialog widget
  • Preventing the user to dismiss the dialog by tapping the background can be done with barrierDismissible: false
  • The ability to dismiss the dialog by using the back button was dealt with wrapping a WillPopScope around everything. The onWillPop argument is filled with a function that does nothing in particular, except for returning false
An animated progress indicator using showDialog over an overlay
The final result

But now that we prevent the user from dismissing the dialog, how are we dismissing it programmatically after the loading has finished, you might ask yourself.
Good question! Since showDialog does eventually nothing else than Navigator.push, we can reverse the operation by popping that from the stack:

void hideOpenDialog() {
  Navigator.of(context).pop();
}

Aaand action!

To see it in action, I prepared a to-be-copied solution based on the sample app of Flutter that has a FloatingActionButton that increases a counter. In the example I simulate that the addition takes 2 seconds (by using a delayed Future). During that operation the user is faced with the above built dialog. Here is what it looks like:

Animation showing the flutter overlay progress indicator in action
The progress indicator in action

If you like what you’ve read, feel free to support me:

🥗Buy me a salad

2 thoughts on “Displaying a progress indicator”

  1. Being relatively new to Flutter and mobile dev in general, this is so simple and straightforward, it’s quite eloquent. Your write-up has given me a base concept to begin merging into my own app as part of a `FutureBuilder` on my auth routes. Thank you for sharing your thought process and approach! (…and your code 🙂 )

    Reply

Leave a Comment