How To Show A Widget While A Asyncronous Task Is Executing And Then Show A Done Widget After It Has Executed In Flutter

- 1 answer

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



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