Free eBook - Flutter Cookbook

4 (1 reviews total)
By Simone Alessandria , Brian Kayfitz
  • A new free eBook every day on the latest in tech
  • 30 permanently free eBooks from our core tech library
  1. Getting Started with Flutter

About this book

Flutter is an open-source framework for building mobile, web, and desktop apps using the Dart language. With this recipe-based guide, which focuses on robust app design and core principles, you’ll learn how to solve cross-platform development issues in a practical way.

The Flutter Cookbook covers error handling and debugging to ensure that your apps run more efficiently. You’ll start by setting up Flutter and customizing your development environment. The book will explain the main tasks involved in app development, such as user interface and user experience (UI/UX) design, API design, and creating animations. Later chapters get you up to speed with routing, retrieving data from web services, and persisting data locally. A dedicated section also focuses on Firebase and its machine learning capabilities. The last chapter is specifically designed to help you create apps for the web and desktop (Windows, Mac, and Linux). Throughout the book, you’ll find recipes that cover the most important features needed to build a cross-platform application, along with insights into running a single codebase on different platforms.

By the end of this Flutter book, you’ll have learned everything you need to be able to write and deliver fully functional apps.

Publication date:
June 2021
Publisher
Packt
Pages
646
ISBN
9781838823382

 
Introduction to Widgets

It's time to finally get our hands dirty with Flutter! By now, you should have your environment set up and have a pretty good handle on Dart, so there shouldn't be any surprises.

In this chapter, we will be building the layout for static elements in Flutter while showing how to build widget trees. Everything in Flutter should be thought of as living in a tree structure. 

Every widget in Flutter is supposed to perform a single small task. On their own, widgets are classes that perform tasks on the user interface. A Text widget displays text. A Padding widget adds space between widgets. A Scaffold widget provides a structure for a screen.

The real power of widgets comes not from any individual class, but from how you can chain them together to create expressive interfaces.

This chapter will cover the following recipes:

  • Creating immutable...
 

Technical requirements

 

Creating immutable widgets

A stateless widget is the primary building block for creating user interfaces. This widget is simple, lightweight, and performant. Flutter can render hundreds of stateless widgets without breaking sweat.

Stateless widgets are immutable. Once they are created and drawn, they cannot be modified. Flutter only has to concern itself with these widgets once. It doesn't have to maintain any complex life cycle states or worry about a block of code modifying them.

In fact, the only way to modify a stateless widget is by deleting it and creating a new one.

 

How to do it...

Start off by creating a brand new flutter project called flutter_layout, either via your IDE or the command line. Don't worry about the sample code generated. We're going to delete it and start from scratch:

  1. Open main.dart and delete everything! Then, type the following code into the editor:
void main() => runApp(StaticApp());

class StaticApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: ImmutableWidget(),
);
}
}
  1. Notice that you have a bunch of red underlines. We need to fix this by importing the material.dart library. This can be done manually, but it's more fun to let your IDE do that job. Move your cursor over the word StatelessWidget.

  2. In VS Code, press Ctrl + ., or Command + . on a Mac. In Android Studio/Intellij, press  Alt + Enter, or Option + Enter on a Mac. This will bring up a dialog where you can choose which file to import...

 

How it works...

Just like every Dart application starts with the main function, so does every Flutter app. But in a Flutter app, you also need to call the runApp function:

void main() => runApp(StaticApp());

This line initializes the Flutter framework and places a StaticApp, which is just another stateless widget, at the root of the tree.

Our root class, StaticApp, is just a widget. This class will be used to set up any global data that needs to be accessed by the rest of our app. However, in this case, it will just be used to kick off our widget tree, which consists of a MaterialApp and the custom ImmutableWidget

One phrase that you frequently see in the official Flutter documentation is, "It's all widgets, all the way down." This phrase implies two things:

  • Every item in Flutter inherits from the widget class. If you want it on the screen, it's a widget. Boxes are widgets. Padding is a widget. Even screens are widgets.
  • The core data structure...
 

Using a Scaffold

Android and iOS user interfaces are based on two different design languages. Android uses Material Design, while Apple has created the Human Interface Guidelines for iOS, but the Flutter team calls the iOS design pattern Cupertino, in honor of Apple's hometown. These two packages, Material and Cupertino, provide a set of widgets that mirror the user experience of their respective platforms.

These frameworks use a widget called Scaffold (CupertinoScaffold in the Cupertino framework) that provides a basic structure of a screen. 

In this recipe, you are going to give your app some structure. You will be using the Scaffold widget to add an AppBar to the top of the screen and a slide-out drawer that you can pull from the left.

 

Getting ready

You should have completed the previous recipe in this chapter before following along with this one.

Create a new file in the project called basic_screen.dart. Make sure that the app is running while you are making these code changes. You could also adjust the size of your IDE so that the iOS simulator or Android emulator can fit beside it:

By setting up your workspace in this way, it will be much easier to see code changes automatically injected into your app (if you are lucky enough to be using two monitors, this does not apply, of course).

 

How to do it...

Let's start by setting up a Scaffold widget:

  1. In basic_screen.dart, type stless to create a new stateless widget and name that widget BasicScreen. Don't forget to import the material library as well:
import 'package:flutter/material.dart';

class BasicScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container();
}
}
  1. Now, in main.dartreplace ImmutableWidget with BasicScreen. Hit  the save button to hot reload and your simulator screen should be completely white:
import 'package:flutter/material.dart';
import './basic_screen.dart';

void main() => runApp(StaticApp());

class StaticApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: BasicScreen(),
);
}
}
  1. Now it's time to bring in the scaffold. In basic_screen.dart, we're going to add the widget that was created in the previous recipe, but bring...
 

How it works...

Scaffold is, as you may guess, a widget. It is usually recommended to use a Scaffold widget as the root widget for your screen, as you have in this recipe, but it is not required. You generally use a Scaffold widget when you want to create a screen. Widgets that do not begin with Scaffold are intended to be components used to compose screens.

Scaffolds are also aware of your device's metrics. AppBar will render differently depending on whether you are on iOS or Android! These are known as platform-aware widgets. When you add an app bar and you run your app on iOS, AppBar formats itself to avoid the iPhone's notch. If you run the app on an iOS device that doesn't have a notch, like the iPhone 8 or an iPad, the extra spacing added for the notch is automatically removed. 

There also other tools in a scaffold that we will cover in the next chapters.

Even if you don't plan on using any of the components that&...
 

Using the Container widget

We've already played around a bit with the Container widget in the previous recipes, but we will build upon what you've seen before and add other features of this versatile widget. In this recipe, you will add some new effects to the existing ImmutableWidget.

 

Getting ready

Before following this recipe, you should have completed the two previous recipes in this chapter, Creating immutable widgets, and Using a scaffold.

I suggest you also leave the app running while you are typing your code, so you can see your changes via hot reload every time you save your file.

 

How to do it...

Let's start by updating the small box in the center and turning it into a shiny ball:

  1. In the ImmutableWidget class, replace the third container with this method:
@override
Widget build(BuildContext context) {
return Container(
color: Colors.green,
child: Padding(
padding: EdgeInsets.all(40),
child: Container(
color: Colors.purple,
child: Padding(
padding: const EdgeInsets.all(50.0),
child: _buildShinyCircle()
),
),
),
);
}
  1. Write the method for the shiny circle. You will be adding BoxDecoration to a Container, which can include gradients, shapes, shadows, borders, and even images.
After adding BoxDecoration, you should make sure to remove the original color property on the container, otherwise, you will get an exception. Containers can have a decoration or a color, but not both.
  1. Add the following code at the end of the ImmutableWidget class:
Widget _buildShinyCircle() {
return...
 

How it works...

Container widgets can add all manner of effects to their child. Like scaffolds, they enable several customizations that can be explored and experimented with.

The primary property you will be designing with is BoxDecoration, which can draw the following:

  • Borders
  • Shadows
  • Colors
  • Gradients
  • Images
  • Shapes (rectangle or circles)

The container itself supports two decorations – the primary background decoration, and a foreground decoration, which is painted on top of the container's child.

Containers can also provide their own transforms (like how you rotated the second container), paddings, and margins.

Sometimes, you may prefer to add properties such as padding inside a container. In other cases, you may use a Padding widget and add Container as its child, as we did in this recipe. Both achieve exactly the same result, so it's up to you really.

In this recipe, we could also have rotated the box by supplying a Matrix4 to the transform property...

 

Printing stylish text on the screen

Almost every app has to display text at some point. Even when we were experimenting with the Dart language in the previous chapter, all those recipes did was display text.

Flutter has a powerful and fast text engine that can render all the rich text that you'd expect from a modern mobile framework.

In this recipe, we will be drawing text with Flutter's two primary widgets – Text and RichText. The Text widget is the most common way to quickly print text on the screen, but you will also occasionally need RichText when you want to add even more style within a single line.

 

Getting ready

To follow along with this recipe, you should have completed all of the previous recipes in this chapter.

Create a new file called text_layout.dart in your project's lib directory.

As always, make sure that your app is running in either a simulator/emulator or an actual device to see the changes in your app in real time with the hot reload feature.

 

How to do it...

Let's get started with some basic text:

  1. In your text_layout.dart file, add the shell for a class called TextLayoutwhich will extend StatelessWidget. Import all the requisite packages:
import 'package:flutter/material.dart';

class TextLayout extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container();
}
}
  1. Open basic_screen.dart and perform these updates so that the TextLayout widget will be displayed underneath ImmutableWidget.  

For the sake of brevity, AppBar and the Drawer code have been ellipted:

import 'package:flutter/material.dart';
import 'package:flutter_layout/immutable_widget.dart';
import 'package:flutter_layout/text_layout.dart';

class BasicScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(...),
body: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children:[
...
 

How it works...

Hopefully, most of the code for the Text widget should be self-evident. It's just a matter of creating hundreds and hundreds of these widgets over time, which will eventually create fluency with this API. The Text widget has some basic properties that warrant discussion, such as text alignment and setting a maximum number of lines, but the real meat is in the TextStyle object. There are several properties in TextStyles that are exhaustively covered in the official documentation, but you will most frequently be adjusting the font size, color, weight, and font.

As a bonus, Text widgets are accessibility-aware out of the box. There is no extra code that you'll need to write. Text widgets respond to the text to speech synthesizers and will even scale their font size up and down if the user decides to adjust the system's font size.

The RichText widget creates another tree of TextSpan, where each child inherits its parent's style but can override it...

 

There's more...

At the beginning of the recipe, did you notice this line?

Theme.of(context).textTheme.headline6,

This is a very common Flutter design pattern known as "of-context," which is used to access data from other parts higher up the widget tree.

Every build method in every widget is provided with a BuildContext object, which is a very abstract sounding name. BuildContext, or context for short, can be thought of as a marker of your widget's location in the tree. This context can then be used to travel up and down the widget tree.

In this case, we're handing our context to the static Theme.of(context) method, which will then search up the tree to find the closest Theme widget. The theme has predetermined colors and text styles that can be added to your widgets so that they will have a consistent look in your app. This code is adding the global headline6 style to this text widget.

 

See also

 

Importing fonts and images into your app

Text and colors are nice, but pictures are worth a thousand words. The process of adding custom images and fonts to your app is a little more complex than you might be expecting. Flutter has to work within the constraints of its host operating systems, and since iOS and Android like to do similar things in different ways, Flutter creates a unified abstraction layer on top of their filesystems.

In this recipe, we will be using asset bundles to add a photo at the top of the screen and use a custom font.

 

Getting ready

You should have completed the previous recipe in this chapter, Printing stylish text to the screen, before following along with this one.

You will add an image to the app. You can get some gorgeous free stock photography from Unsplash. Download this beach image by Khachik Simonian as well: https://unsplash.com/photos/nXOB-wh4Oyc.

 

How to do it...

Let's update the previous recipe's code with some new fonts:

  1. Open the pubspec.yaml file in the root folder of your project. 

  2. In the pubspec.yaml file, add the google_fonts package in the dependencies section, but be careful. YAML is one of the few languages where white space matters, so be sure to put the google_fonts dependency precisely under flutter, as shown here:

dependencies:
flutter:
sdk: flutter
google_fonts: ^2.0.0
  1. After this is done, run flutter packages get to rebuild your asset bundle.

  2. We can now add any Google font to the text widgets in text_layout.dart.  Add the google_fonts  import at the top of the file:

import 'package:google_fonts/google_fonts.dart';
  1. Update the first Text widget to reference the leckerliOne font:
Text(
'Hello, World!',
style: GoogleFonts.leckerliOne(fontSize: 40),
),

The leckerliOne font will now be rendered on the screen:

  1. Now you will...
 

How it works...

In this recipe, you have seen two common features in Flutter: choosing fonts for your Text widgets, and adding images to your screens.

When working with Google Fonts, adding them to your project is extremely easy. You just need to add the google_fonts package dependency in the pubspec.yaml file to your app, as you did with the following command:

google_fonts: ^2.0.0

There are currently about 1,000 fonts you can use for free in your apps with Google Fonts! Have a look at the official site, https://fonts.google.com/, to choose the right one for your apps.

When you want to use the google_fonts package in one or more of your screens, you need to import the package at the top of the file. Youcan do this in the text_layout.dart file with the help of the following command:

import 'package:google_fonts/google_fonts.dart';

From there, you just need to use the package. You add the GoogleFonts widget to the style property of your Text:

 style: GoogleFonts.leckerliOne...
 

About the Authors

  • Simone Alessandria

    Simone Alessandria wrote his first program when he was 12. It was a text-based fantasy game for the Commodore 64. Now, he is a trainer (MCT), author, speaker, passionate software architect, and always a proud coder. He is the founder and owner of Softwarehouse. His mission is to help developers achieve more through training and mentoring. He has authored several books on Flutter, including Flutter Projects, published by Packt, and web courses on Pluralsight and Udemy.

    Browse publications by this author
  • Brian Kayfitz

    Brian's career had him working on video games, eCommerce, productivity, finance, and travel apps. After spending years working as an iOS and Android developer, he sees Flutter as the next big pillar for mobile.

    Browse publications by this author

Latest Reviews

(1 reviews total)
Bouquin bien clair et précis

Recommended For You

SwiftUI Projects

Learn SwiftUI by designing and building complex user interfaces for watchOS, iPadOS, and iOS with the help of projects including a financial app, a sports news app, and a POS system

By Craig Clayton
How to Build Android Apps with Kotlin

Master the fundamentals of Android programming and apply your skills to create scalable and reliable apps using industry best practices

By Alex Forrester and 3 more
Full-Stack React, TypeScript, and Node

Discover the current landscape of full-stack development and how to leverage modern web technologies for building production-ready React.js applications to deploy on AWS

By David Choi
Vue.js 3 Cookbook

Explore the new features of Vue.js 3 and discover best practices for building fault-tolerant and professional frontend web applications

By Heitor Ramon Ribeiro