Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reload data when using useFuture flutter hook

I'm using Flutter hooks to fetch data by combining useMemorized and useFuture like this:

final _latestDocsFuture =
    useMemoized(() => getLatestDocs());
final _latesetDocsSnapshot = useFuture(_latestDocsFuture);

The problem with this hook is I can't re-trigger the useFuture to re-fetch the data in case of an error (allowing the user to tap on a button to try and fetch the data again). Is there any method that can let me re-trigger the useFuture hook?

like image 543
Samir Ait abdelkoui Avatar asked Oct 17 '25 11:10

Samir Ait abdelkoui


1 Answers

The useMemoized hook accepts a list of keys that can be used to create new instances of the Future, which would cause useFuture to run again.

I'd suggest using the UniqueKey class to achieve this

final reloadKey = useState(UniqueKey());
final latestDocsFuture = useMemoized(() => getLatestDocs(), [reloadKey.value],);
final latestDocsSnapshot = useFuture(latestDocsFuture);

Then whenever you wish to reload, you can update the value of reloadKey

reloadKey.value = UniqueKey();
like image 82
Luke Greenwood Avatar answered Oct 20 '25 02:10

Luke Greenwood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!