Solved: How to show a widget while a asyncronous task is executing and then show a done widget after it has executed in flutter


Asked by Joel on November 27, 2021 (source).

I wanted to make a asynchronous loading dialog, that retrieves data from a database(this is the asynchronous task) and once it is done, i want to show a dialog box that shows the data retrieved. Meaning, I want to show a loading dialog box widget while the data is being retrieved from the database, and once the data is retrieved, show it on the screen using a dialog box


Question answered by Yeasin S (source).

In this we need to handle tree scenario,

  • Before data call, show nothing
  • on future call, show progressBar
  • after fetch, use data

Using two nullable variable to handle this situation

Simply replace the widget according to your need.

class _WelcomeScreenState extends State<WelcomeScreen> {
  Future<int> fecthData() async {
    return Future.delayed(
      Duration(seconds: 3),
      (value) => 4,

  bool? _isLoading;
  int? data;

  Widget build(BuildContext context) {
    return Scaffold(
      body: LayoutBuilder(
        builder: (context, constraints) => Column(
          children: [
                onPressed: () async {
                  setState(() {
                    _isLoading = true; //set true while fetching
                  data = await fecthData();
                  setState(() {
                    _isLoading = false; //set false while fetching
                child: Text("Fetch")),
            if (_isLoading == true) CircularProgressIndicator(),
            if (data != null) Text("${data!}") // if you have data show it