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?
3
Answers
You can use
FutureBuilder
to load data like this:You can use FutureBuilder or via using turnery operators.
Here is an example of loadData using the provider. If you don’t want to eager load the data, just remove initState() method.