Home > OS >  How to show a widget while a asyncronous task is executing and then show a done widget after it has
How to show a widget while a asyncronous task is executing and then show a done widget after it has

Time:11-27

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

CodePudding user response:

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),
    ).then(
      (value) => 4,
    );
  }

  bool? _isLoading;
  int? data;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: LayoutBuilder(
        builder: (context, constraints) => Column(
          children: [
            ElevatedButton(
                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
          ],
        ),
      ),
    );
  }
}

CodePudding user response:

There point comes when you need to show loading bar or circular progress indicator while fetching data from internet in Flutter. There are multiple ways you can show loading bar till data is not fetched. Some are:

  • Use setstate((){}) method.
  • Use State Management like GetX, Bloc, Provider.
  • Use FutureBuilder()
  • Use StreamBuilder() You can use any one of them as the logic behind all is same. The logic is simple: Suppose, there is one bool variable which is set to false initially.Till data is not fetched completely, you will need to show loading bar and for this, that bool variable will be set true . As soon as all the data fetched, we will set that bool variable to false again. And according to the value of that bool variable ,you will need to show widgets.Click here
  • Related