List View

In order to provide a scrollable list that contains multiple custom widgets we’re going to use the ListView class. But before that, we’re going to transform our already existing stateless widget HomeScreen to stateful widget and use Flutter classes StatefulWidget and State.

Because the data that we work with can change during the life time of the HomeScreen widget StatelessWidget is not the right choice anymore.

Let’s take a closer look at stateful widgets.

Stateful Widgets

In case that we know that the widget that we’re implementing is dynamic, we want to implement a stateful widget instead of a stateless widget. As the name stateful widget suggests, stateful widgets have a state. The state can change during the life cycle of the widget. Such changes can be made by the user, who interacts with elements of the user interface. As soon as the state changes, the widget gets redrawn.

The implementation consists of two subclasses:

Subclass StatefulWidget — contains a definition of the widget

— contains a definition of the widget Subclass State — builds the widget and includes its state

Implementation

We’re going to implement the following pattern.

Our HomeScreen widget is going to be the parent widget that manages the state — list of recipes and the list of favorites. It’s going to be our active widget. If the state changes, the active widget tells its inactive widgets to update.

At the end of today’s implementation the class HomeScreen is going to manage the state that RecipeCard widgets are based on. Furthermore, it is going update them when the user modifies the list of his or her favorites by interacting with the UI of a RecipeCard widget. Tapping on a favorites button is going to update the list of favorites by the method _handleFavoritesListChanged , that you can find in the code below.

Active parent widget manages the state of inactive widgets

Let us do it step by step.

Here is the basic implementation of the list view:

lib/ui/screens/home.dart

As you can see, we use ListView.builder in the private method _buildRecipes . The constructor builder of ListView class works pretty similar to for loops. It awaits a count of widgets to build in the itemsCount parameter to know how many times the builder should add a widget to the list view.

The ListView object is wrapped by an Expanded object to use all available space in the column.

Let’s look at the result:

The result has definitely potential for further improvements.