flutterasync-awaitproviderfetching-strategy

What is the correct way of loading some data from database in Flutter?


Considering we have a function like following that loads up data from database:

  loadData() async {
    loadedData = await loadingData();
    return loadedData;
  }

And we want to use this loadedData inside the same or other class/widget using Provider package.

I tried many ways like putting loadData() inside initState() or didChangeDependencies() like following:

  @override
  void didChangeDependencies() async {
    super.didChangeDependencies();
    data = await Provider.of<>(context , listen: false).loadData();
  }

Or using Consumer or trying to pass data using ChangeNotifierProxyProvider at the startup of the application but still have problems most of the time and getting errors like null value errors or some other related errors(Can't remember at the moment).

I like to know what is the correct way of fetching data from database and wait for data in a Widget?

For example I know if I change (listen: false) to (listen: true) within the Provider command I can read data but it seems it updates the app very much and I can hear the rising noise of the CPU fan that I don't like it!

Please give me a simple code example/snippet to understand the correct way of doing that?


Solution

  • You can use FutureBuilder to load data like this:

    class MyWidget extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return FutureBuilder(
          future: Provider.of<MyData>(context, listen: false).loadData(),
          builder: (BuildContext context, AsyncSnapshot<MyData> snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(
                child: CircularProgressIndicator(),
              );
            } else if (snapshot.hasError) {
              return Center(
                child: Text('Error: ${snapshot.error}'),
              );
            } else {
              MyData data = snapshot.data!;
              // Use the loaded data to build your widget
              return Text(data.someProperty);
            }
          },
        );
      }
    }