Declarative Animation in Flutter
2019-07-25This article will go over methods of animating Flutter widgets based on state, with some solutions to make it a little more straightforward. The Short of It If you know what you’re looking for, are familiar with Flutter animations and Widget lifecycles, and just want to know how to trigger animations based on state changes without reading a whole article, the answer is that you need to override the method in . Here’s a quick example, followed by some discussion on Flutter animations and generalized solutions. We will go into much greater detail about below. The Long of It Flutter’s declarative programming style works extremely well for building a UI and populating it with data, allowing changes in the data state to update the UI state automatically. It’s very easy to tell the framework that, in terms of the UI, you would like something to be different based on the state. However it is less straightforward to tell the framework that you would like something to happen based on the state. As an example, let’s say we’re using a , and we want different widgets to be visible based on the state of the stream. If the stream has no data, a widget with a loading indicator should slide into view, and, importantly, should slide back out of view when the stream has data. The common way to handle loading states for streams is something like the following: This will cause the screen to transition completely between one widget and the other when the status of the snapshot data changes. However, let’s say that we actually want to have the Loading widget sit on top of the DataWidget when the stream has no data, either because the DataWidget still has some interactivity even when it doesn’t have stream data, or because we just like the look of a floating progress indicator. We might do something like this: Okay, so now our LoadingWidget sits on top of the DataWidget when the stream has no data, but rather than just appearing on top, we want it to slide in from the top of the screen. There are several ways to do this, but the most straightforward might be to use either a widget, or an widget. Both have some drawbacks in this scenario. The widget requires that it be provided with an , which must be checked and controlled from somewhere within the method. This introduces a lot of extra code and, more importantly, our method is suddenly beset by a big block of imperative code nestled uncomfortably amist all of our nice declarative UI code. It only gets worse if there are…