3

I just started using Flutter Hooks and have been trying to understand how I would initialize a useState hook with a value that is retrieved asynchronously? In my case, from SharedPreferences

Normally you would say final boolValue = useState(false)

In my case I need to first evaluate a Future<bool> then set my subsequent call like final boolVal = useState(async value)

how can I achieve this using hooks, would I have to resolve the value before entering this widget and simply pass it down?

swedishcheef
  • 549
  • 2
  • 11
  • 25
  • 1
    Use a `FutureBuilder` widget to get the initial value first. [More info on that (it's pretty informative!](https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html) – Riwen Sep 28 '20 at 19:13
  • 1
    @Riwen rather than using `useFuture` ? – swedishcheef Sep 28 '20 at 19:17
  • Having the widget wait for an `async` call before it can initialize its state would cause the widget (and therefore the app) to hang while waiting for the call to complete. It would be much cleaner to set the initial value of the state to be some neutral value and then update it once the future completes. – Abion47 Sep 28 '20 at 19:38
  • 1
    @Abion47 so that's what I did, and I thought it was a 'hack'. I used `useEffect` and passed an empty [] to only make it run a single time. I initialized my state to a neutral value like so `final boolVal = useState(false)` then set `boolVal.value` inside `useEffect` once the Future resolved. So maybe that is not really that much of a hack then? – swedishcheef Sep 28 '20 at 19:45

1 Answers1

4

How about using HookBuilder?

final future = useMemoized(()=> someAsyncFunction());
final snapshot = useFuture(future);

...

if(snapshot.hasData){
   return HookBuilder(
    builder : (_) {
      final state = useState(snapshot.data);
      //... return widget using state.value
    })

}
hyobbb
  • 332
  • 1
  • 9