Flutter MDC Codelabs: Some extra details

I’m trying to learn my 15 year old son and his nephew some basic Flutter. So, I asked them last week to try the “MDC 10X Codelabs”. They managed to get it working, but I hope to give them some extra insights with the info below:

Stateless vs Stateful widgets

When you create an app with Flutter, then you always have to create some widgets: pages or smaller parts of the UI. You will then have to derive your widget from the StatelessWidget or StatefulWidget class:

Derive from StatelessWidget if the appearance of your widget does NOT change (not 100%, but that’s the easiest way to understand). Examples are: a contact screen, the individual list items of a list view, etc…

When the appearance will change, then you probably have to derive from StatefulWidget. Then you basically have to create 2 classes: the widget itself & a state class.

Let’s create for each case an example to compare the code:

  • Ex1Page: a stateless widget
  • Ex2Page: a stateful widget

Stateless widget: Ex1Page

The code for a stateless widget is straightforward:

You then need to replace the 3 dots (…) inside the build method with your specific content.

Stateful widget: Ex2Page

For a stateful widget you have to create 2 classes:

Notice that the build method is now part of the State class. Again replace the 3 dots with you content.

MDC-101 Flutter: Material Components Basics

Let’s have a look to the first code lab: MDC-101. There you have to complete the login page:

The login page is a stateful widget (because it derives from StatefulWidget) and as such you have 2 classes: LoginPage & LoginPageState.

In the build method of the state class you create the user interface. This is a hierarchical structure of other widgets:

Let’s try to visualize this a bit better:

If you want to understand what “Scaffold” and “SafeArea” exactly do, then have a look to my previous post “Flutter: some basic widgets illustrated”. The other widgets are self explanatory.

MDC-102 Flutter: Material Structure and Layout

In the second code lab you need to finalize a grid of products. The people that designed the lab decided to implement this page as a stateless widget:

I will leave out the code for the build method, but basically they create this structure:

Notice that an AppBar was placed inside the Scaffold. Then there is also a separate methd “_buildGridCards” that creates a list of cards. Each card has the following structure:

Conclusion

This was a short post to visualize the code created in the MDC codelabs. Hope it helps to understand better!

Partner at Appdnd: agency specialized in App Design & Development. Interests: technology, startups, travel & watersports.