flutterdartflutter-hooks

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?


Solution

  • 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();