Handling Async functions in Flutter’s initState()

Rizky Syawal
2 min readOct 4, 2020

Side-note: most of the articles I’m writing will mostly be reminders for myself in the near future if I ever forgot what most of the features does. But anywho if you find this helpful then I’m glad.

So initState() is a really useful method in Flutter that I’ve been using a lot lately, and for anyone who doesn’t know about initState, in simple terms it allows you to initialize variables, call different methods before a stateful widget is built.

Here i initialized the a variable called value and called a method addValue that increments the value by one before the widget is built. Then I can use the variable i just initialized in initState on my finished widget

After using it for a while I came across an inevitable problem, async functions. The problem I encountered was when I was trying to overwrite my variable with an async function that returns a value.

Here i created a new async function called newValue that returns an Integer, and I tried to reinitialize my value variable with the newValue method.

In this problem, instead of returning an Integer in the value variable (the one we reinitialized in initState()), it returns a Future<dynamic>.

To solve this problem and actually return an Integer, we need to utilize .then method as well as setState() method.

Since our method is an async function, we need to wait a certain amount of time for it to complete, so before we reinitialize the value variable we need to wait for the newValue method to actually return an Integer. As we can see we in the code snippet above, we wait for the newValue method to return a response, and then we reinitialize the value variable with the response we got using the setState method.

And voila, the $value text returns 124!

Hope this article helps.

P.S. initState methods can only be used in stateful widgets. I keep forgetting!

--

--

Rizky Syawal

Software Engineer who still have a lot to learn.