Lifecycle and Rendering in Flutter

In the last couple of weeks I’ve been taking a look over Flutter again after reading an article about it by GeekyAnts. I might write an article comparing it to React Native in the future because there are a lot of areas where it offers a better developer experience(and some gaps too), but today I mainly want to talk about an issue I had with figuring out the lifecycle events of a Widget.

The Issue

I was testing out Flutter’s core Navigation(which is great by the way) and I wanted to make some kind of animated Splash Screen. The idea was to load some persisting values then show an animation on a logo on the screen and transition to the Home Screen of the app. Usually in React Native I can rely on something like componentDidMount to run this kind of logic. I went searching for something similar in Flutter and I couldn’t find it. I tried running the tasks after the super in initState in the State for the screen’s Widget. This didn’t work either. Instead I was greeted with a pretty clear warning.

Flutter rendering er

You can’t transition or modify state while a Widget is still building. This makes perfect sense but I was kind of lost again as to where I should put the loading logic. After further investigation I found out about WidgetsBindingObserver but it still didn’t seem like exactly what I was searching for.

The Solution

After a little more research I came across a method from Dart’s async library called scheduleMicroTask. When I wrapped my transition logic in this inside initState the error disappeared and things worked perfectly:

Then after playing around a little more I realized that making the method an async method also had the same effect and worked well:

Wrap Up

There are probably better ways to construct a Splash Screen. A lot of people are actually against animations and believe in a speedy start up experience. In any case I hope this information is useful to somebody else, one of the downsides of Flutter is it is a little newer than React Native and has less tutorials and information readily available. That should all change with time but.