Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Hooks - useState initial value

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?

like image 487
swedishcheef Avatar asked Oct 21 '25 18:10

swedishcheef


1 Answers

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
    })

}
like image 121
hyobbb Avatar answered Oct 24 '25 08:10

hyobbb



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!