As you know, everything in Flutter is a widget. But how do you know which widget to use when? In this chapter, you’ll explore three categories of basic widgets, which you can use for:
Structure and navigation
Displaying information
Positioning widgets
By the end of this chapter, you’ll use those different types of widgets to build the foundation of an app called Fooderlich, a social recipe app. You’ll build out the app’s structure and learn how to create three different recipe cards: the main recipe card, an author card and an explore card.
Ready? Dive in by taking a look at the starter project.
Locate the projects folder and open starter. If your IDE has a banner that reads ‘Pub get’ has not been run, click Get dependencies to resolve the issue.
Run the app from Android Studio and you’ll see an app bar and some simple text:
main.dart is the starting point for any Flutter app. Open it and you’ll see the following:
import 'package:flutter/material.dart';
void main() {
// 1
runApp(const Fooderlich());
}
class Fooderlich extends StatelessWidget {
// 2
const Fooderlich({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
// TODO: Create theme
// TODO: Apply Home widget
// 3
return MaterialApp(
// TODO: Add theme
title: 'Fooderlich',
// 4
home: Scaffold(
// TODO: Style the title
appBar: AppBar(title: const Text('Fooderlich')),
// TODO: Style the body text
body: const Center(child: Text('Let\'s get cooking 👩🍳')),
),
);
}
}
Take a moment to explore what the code does:
Everything in Flutter starts with a widget. runApp() takes in the root widget Fooderlich.
Every stateless widget must override the build() method.
The Fooderlich widget starts by composing a MaterialApp widget to give it a Material Design system look and feel. See https://material.io for more details about it.
The MaterialApp widget contains a Scaffold widget, which defines the layout and structure of the app. The scaffold has two properties: an appBar and a body. An Appbar’s title contains a Text widget. The body has a Center widget, whose child property is a Text widget.
Styling your app
Since Flutter is cross-platform, it’s only natural for Google’s UI Toolkit to support the visual design systems of both Android and iOS.
Android uses the Material Design system, which you’d import like this:
import 'package:flutter/material.dart';
iOS uses the Cupertino system. Here’s how you’d import it:
import 'package:flutter/cupertino.dart';
To keep things simple, a rule of thumb is to pick only one design system for your UI. Imagine having to create if-else statements just to manage the two designs, let alone support different transitions and OS version compatibility.
Throughout this book, you’ll learn to use the Material Design system. You’ll find the look and feel of Material Design is quite customizable!
Note: Switching between Material and Cupertino is beyond the scope of this book. For more information about what these packages offer in terms of UI components, check out:
Now that you have settled on a design, you’ll set a theme for your app in the next section.
Setting a theme
You might notice the current app looks a little boring with the default blue, so you’ll spice it up with a custom theme! Your first step is to select the font for your app to use.
Using Google fonts
The google_fonts package supports over 900 fonts to help you style your text. It’s already included in pubspec.yaml and you have already added it to the app when clicking Pub Get before. You’ll use this package to apply a custom font to your theme class.
Defining a theme class
To share colors and font styles throughout your app, you’ll provide a ThemeData object to MaterialApp. In the lib directory, open fooderlich_theme.dart, which contains a predefined theme for your app.
Define a TextTheme called lightTextTheme, which uses the Google font Open Sans and has a predefined font size and weight. Most importantly, the color of the text is black.
Then it defines darkTextTheme. In this case, the text is white.
Next, it defines a static method, light, which returns the color tones for a light theme using the lightTextTheme you created in step 1.
Finally, define a static method, dark, which returns the color tones for a dark theme using the darkTextTheme you created in step 2.
Your next step is to utilize the theme.
Using the theme
In main.dart, import your theme by adding the following beneath the existing import statement:
import 'fooderlich_theme.dart';
Then replace the comment //TODO: Create theme with the following:
final theme = FooderlichTheme.dark();
To apply the new theme replace the comment // TODO: Add theme with the following:
theme: theme,
Next replace the comment // TODO: Style the title and the line below it with the following:
Save your changes. Thanks to hot reload, you’ll see the updated theme nearly immediately.
To see the difference between light and dark mode, change the theme between FooderlichTheme.dark() and FooderlichTheme.light(). The two themes look like this:
Note: It’s generally a good idea to establish a common theme object for your app — especially when you work with designers. That gives you a single source of truth to access your theme across all your widgets.
Next, you’ll learn about an important aspect of building an app — understanding which app structure to use.
App structure and navigation
Establishing your app’s structure from the beginning is important for the user experience. Applying the right navigation structure makes it easy for your users to navigate the information in your app.
Fooderlich uses the Scaffold widget for its starting app structure. Scaffold is one of the most commonly-used Material widgets in Flutter. Next, you’ll learn how to implement it in your app.
Using Scaffold
The Scaffold widget implements all your basic visual layout structure needs. It’s composed of the following parts:
AppBar
BottomSheet
BottomNavigationBar
Drawer
FloatingActionButton
SnackBar
Scaffold has a lot of functionality out of the box!
The following diagram represents some of the aforementioned items as well as showing left and right nav options:
As you build large-scale apps, you’ll start to compose a staircase of widgets. Widgets composed of other widgets can get really long and messy. It’s a good idea to break your widgets into separate files for readability.
To avoid making your code overly complicated, you’ll create the first of these separate files now.
Scaffold needs to handle some state changes, via a StatefulWidget. Your next step is to move code out of main.dart into a new StatefulWidget named Home.
In the lib directory, create a new file called home.dart and add the following:
import 'package:flutter/material.dart';
// 1
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
// TODO: Add state variables and functions
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
'Fooderlich',
// 2
style: Theme.of(context).textTheme.headline6,
),
),
// TODO: Show selected tab
body: Center(
child: Text('Let\'s get cooking 👩🍳',
// 3
style: Theme.of(context).textTheme.headline1)),
// TODO: Add bottom navigation bar
);
}
}
Most of the Scaffold code looks like what you have in main.dart, but there are a few changes:
Your new class extends StatefulWidget.
The AppBar style now reads: Theme.of(context).textTheme.headline6 instead of: theme.textTheme.headline6. Theme.of(context) returns the nearest Theme in the widget tree. If the widget has a defined Theme, it returns that. Otherwise, it returns the app’s theme.
As with the AppBar, you’ve also updated the Text style to use the Theme.of(context).
Go back to main.dart, which you need to update so it can use the new Home widget. At the top, add the following import statement:
import 'home.dart';
Next replace // TODO: Apply Home widget and all the return MaterialApp()code below it with the following:
_selectedIndex keeps track of which tab is currently selected. The underscore in _selectedIndex signifies it’s private. The selected index is the state being tracked by _HomeState.
Here, you define the widgets that will display on each tab. For now, when you tap between the different tab bar items, it shows container widgets of different colors. Soon, you’ll replace each of these with card widgets.
This function handles tapped tab bar items. Here, you set the index of the item that the user pressed. setState() notifies the framework that the state of this object has changed, then rebuilds this widget internally.
Note: In the next chapter, you’ll learn more about how widgets work under the hood. Stay tuned.
Next, locate // TODO: Show selected tab and replace it and the body in the Scaffold with:
body: pages[_selectedIndex],
As the framework rebuilds the widgets, it displays the container widget for the selected tab bar item.
Indicating the selected tab bar item
Now, you want to indicate to the user which tab bar item they currently have selected. Locate // TODO: Set selected tab bar and add the following code:
currentIndex will tell the bottom navigation bar which tab bar item to highlight.
When the user taps on a tab bar item, it calls the _onItemTapped handler, which updates the state with the correct index. In this case, it changes the color.
Because you’ve made changes to the state, you have two options to see the changes. You can either stop your app and restart it, which takes a bit of time, or you can use hot restart, which rebuilds your app in a matter of seconds.
Press the Hot Restart button on the Run window to see how fast it is:
After restarting, your app will look different for each tab bar item, like this:
Now that you’ve set up your tab navigation, it’s time to create beautiful recipe cards!
Creating custom recipe cards
In this section, you’ll compose three recipe cards by combining a mixture of display and layout widgets.
Display widgets handle what the user sees onscreen. Examples of display widgets include:
Text
Image
Button
Layout widgets help with the arrangement of widgets. Examples of layout widgets include:
Apply a padding of 16 on all sides of the box. Flutter units are specified in logical pixels, which are like dp on Android.
Constrain the container’s size to a width of 350 and a height of 450.
Apply BoxDecoration. This describes how to draw a box.
In BoxDecoration, set up DecorationImage, which tells the box to paint an image.
Set which image to paint in the box using an AssetImage, an image found in the starter project assets.
Cover the entire box with that image.
Apply a corner radius of 10 to all sides of the container.
Save your changes to hot reload. Your app now looks like this:
Much better! But you still need to tell the user what they’re looking at.
Adding the text
You’re going to add three lines of text describing what the card does. Start by adding the following import statement to the top of the card1.dart file so that you can use your Theme:
import 'fooderlich_theme.dart';
Next locate // TODO: Add a stack of text and replace it with the following:
For the relevant Text, you apply a Positioned widget. That widget controls where you position the Text in the Stack. Here are the positions you’re using:
The category, Editor’s Choice, stays where it is. Remember, Container already applies a padding of 16 on all sides.
You place the title 20 pixels from the top.
Here, you position the description 30 pixels from the bottom and 0 to the right.
Finally, you position the chef’s name 10 pixels from the bottom-right.
After these updates, the app looks like this:
Great, the first card is finished now. It’s time to move on to the next!
Composing Card2: the author card
It’s time to start composing the next card, the author card. Here’s how it will look by the time you’re done:
Despite the differences in appearance, Card2 is similar to Card1. It’s composed of the following widgets:
A Container with a BoxDecoration displaying an image with rounded corners.
A custom author widget that displays the author’s profile picture, name and job title.
Text widgets — but this time, notice Smoothies has a vertical rotation.
IconButton with a heart on the top-right.
In the lib directory, create a new file called card2.dart. Add the following code:
CircleImage has two parameters: imageProvider and imageRadius.
The imageRadius and imageProvider property declarations.
CircleAvatar is a widget provided by the Material library. It’s defined as a white circle with a radius of imageRadius.
Within the outer circle is another CircleAvatar, which is a smaller circle that includes the user’s profile image. Making the inner circle smaller gives you the white border effect.
Setting up the AuthorCard widget
In the lib directory, create a new file called author_card.dart. Add the following code:
Notice that the container has two Row widgets nested within each other. Here’s what the code does:
The inner Row groups the CircleImage and the author’s Text information.
Applies 8 pixels of padding between the image and the text.
Lays out the author’s name and job title vertically using a Column.
Hot reload and tap Card2’s tab bar button. Your app will now look like this:
Looking good, but there are a few important elements you still need to add.
Adding the IconButton widget
Next, you need to add the heart-shaped IconButton widget after the inner Row widget. The user will click this icon when they want to favorite a recipe.
Start by locating // TODO 2: add IconButton and replacing it with the code below:
When the user presses the icon, display a snackbar.
Note: A snackbar is useful to briefly display information to users when an action has taken place. For example, when you delete an email, you can provide a user with an action to undo. In this case, the snackbar will tell the user that they have liked a recipe.
When you press the heart icon, your app will look like this:
Next, still in author_card.dart, locate // TODO 3: add alignment and replace it with the following:
The outer Row widget applies a spaceBetween alignment. This adds extra space evenly between the outer row’s children, placing the IconButton at the far right of the screen.
Just one important element left to add: the text.
Composing the text
Return to card2.dart, and add the theme import:
import 'fooderlich_theme.dart';
Then locate // TODO 4: add Positioned text and replace it with the following:
Notice how convenient it is to use FooderlichTheme to apply text styles.
Now, take a look at the code:
With Expanded, you fill in the remaining available space.
Apply a Stack widget to position the texts on top of each other.
Position the first text 16 pixels from the bottom and 16 pixels from the right.
Finally, position the second text 70 pixels from the bottom and 16 pixels from the left. Also apply a RotatedBox widget, which rotates the text clockwise three quarterTurns. This makes it appear vertical.
After saving and hot reloading, Card2 will look like this:
And that’s all you need to do for the second card. Next, you’ll move on to the final card.
Note: If you are running the app on a smaller device you may see a warning on the AuthorCard widget. This is because the text overflows the container. You can solve this by wrapping the AuthorCard widget in a FittedBox widget.
Composing Card3: the explore card
Card3 is the last card you’ll create for this chapter. This card lets the user explore trends to find the recipes they want to try.
The following widgets compose Card3:
Container and BoxDecoration display image and rounded corners, similar to the cards above.
You use a second Container to make the image darker and translucent so the white text is easier to read.
Show an icon and the title.
Show a collection of Chip widgets, which display recipe attributes like Healthy or Vegan.
In the lib directory, create a new file called card3.dart. Add the following code:
import 'package:flutter/material.dart';
import 'fooderlich_theme.dart';
class Card3 extends StatelessWidget {
const Card3({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Center(
child: Container(
constraints: const BoxConstraints.expand(
width: 350,
height: 450,
),
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/mag2.png'),
fit: BoxFit.cover,
),
borderRadius: BorderRadius.all(Radius.circular(10.0)),
),
child: Stack(
children: [
// TODO 5: add dark overlay BoxDecoration
// TODO 6: Add Container, Column, Icon and Text
// TODO 7: Add Center widget with Chip widget children
],
),
),
);
}
}
Similar to the previous cards, this sets up the basic container and box decorations for your card.
The initial setup of Card3 is just like Card1 and Card2. In home.dart add the needed import at the top of the file:
import 'card3.dart';
Next, locate // TODO: Replace with Card3 and replace it and the container with the following:
const Card3(),
Perform a hot restart by clicking the button in the Run panel.
Tap the Card3 tab bar item. Your app will look like this:
So far, the card just has the typical card theme and the image. You’ll add the other elements next.
Composing the dark overlay
To make the white text stand out from the image, you’ll give the image a dark overlay. Just as you’ve done before, you’ll use Stack to overlay other widgets on top of the image.
In card3.dart, locate // TODO 5: add dark overlay BoxDecoration add replace it with the following code in the Stack:
Wrap is a layout widget that attempts to lay out each of its children adjacent to the previous children. If there’s not enough space, it wraps to the next line.
Place the children as close to the left, i.e. the start, as possible.
Apply a 12-pixel space between each child in the main axis.
Apply a 12-pixel space between each child in the cross axis.
Save your changes and hot restart. Now, your card looks like this:
Add more Chip widgets by duplicating the Chip() code above. This gives you the chance to see the Wrap layout widget in action, as shown below:
You did it! You’ve finished this chapter. Along the way, you’ve applied three different categories of widgets. You learned how to use structural widgets to organize different screens, and you created three custom recipe cards and applied different widget layouts to each of them.
Well done!
Key points
Three main categories of widgets are: structure and navigation; displaying information; and, positioning widgets.
There are two main visual design systems available in Flutter, Material and Cupertino. They help you build apps that look native on Android and iOS, respectively.
Using the Material theme, you can build quite varied user interface elements to give your app a custom look and feel.
It’s generally a good idea to establish a common theme object for your app, giving you a single source of truth for your app’s style.
The Scaffold widget implements all your basic visual layout structure needs.
The Container widget can be used to group other widgets together.
The Stack widget layers child widgets on top of each other.
Where to go from here?
There’s a wealth of Material Design widgets to play with, not to mention other types of widgets — too many to cover in a single chapter.
Fortunately, the Flutter team created a Widget UI component library that shows how each widget works! Check it out here: https://gallery.flutter.dev/
In this chapter, you got started right off with using widgets to build a nice user interface. In the next chapter, you’ll dive into the theory of widgets to help you better understand how to use them.