Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Flutter Cookbook
Flutter Cookbook

Flutter Cookbook: Over 100 proven techniques and solutions for app development with Flutter 2.2 and Dart

Arrow left icon
Profile Icon Simone Alessandria Profile Icon Kayfitz
Arrow right icon
€26.98 €29.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2 (16 Ratings)
eBook Jun 2021 646 pages 1st Edition
eBook
€26.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Simone Alessandria Profile Icon Kayfitz
Arrow right icon
€26.98 €29.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2 (16 Ratings)
eBook Jun 2021 646 pages 1st Edition
eBook
€26.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€26.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Flutter Cookbook

Dart: A Language You Already Know

At its heart, Dart is a conservative programming language. It was not designed to champion bold new ideas, but rather to create a predictable and stable programming environment. The language was created at Google in 2011, with the goal of unseating JavaScript as the language of the web.

JavaScript is a very flexible language, but its lack of a type system and misleadingly simple grammar can make projects very difficult to manage as they grow. Dart aimed to fix this by finding a halfway point between the dynamic nature of JavaScript and the class-based designs of Java and other object-oriented languages. The language uses a syntax that will be immediately familiar to any developer who already knows a C-style language.

This chapter also assumes that Dart is not your first programming language. Consequently, we will be skipping the parts of the Dart language where the syntax is the same as any other C-style language. You will not find anything in this chapter about loops, if statements, and switch statements; they aren't any different here from how they are treated in other languages you already know. Instead, we will focus on the aspects of the Dart language that make it unique.

In this chapter, we will cover the following recipes, all of which will function as a primer on Dart:

  • Declaring variables  var versus final versus const
  • Strings and string interpolation
  • How to write functions
  • How to use functions as variables with closures
  • Creating classes and using the class constructor shorthand
  • Defining abstract classes
  • Implementing generics
  • How to group and manipulate data with collections
  • Writing less code with higher-order functions
  • Using the cascade operator to implement the builder pattern
  • Understanding Dart Null Safety
If you are already aware of how to develop in Dart, feel free to skip this chapter. We will be focusing exclusively on the language here and will then cover Flutter in detail in the next chapter.

Technical requirements

This chapter will focus purely on Dart instead of Flutter. There are two primary options for executing these samples:

  • DartPad (https://dartpad.dartlang.org): DartPad is a simple web app where you can execute Dart code. It's a great playground for trying out new ideas and sharing code.
  • IDEs: If you wish to try out these samples locally with complete code support, then you can use either Visual Studio Code or IntelliJ.

Declaring variables – var versus final versus const

Variables are user-defined symbols that hold a reference to some value. They can range from a single number to large object graphs. It is virtually impossible to write a useful program without at least one variable. You can probably argue that almost every program ever written can be boiled down to taking in some input, storing that data in a variable, manipulating the data in some way, and then returning an output. All of this would be impossible without variables.

Recently, a new trend has appeared in programming that emphasizes immutability. This means that once the values are stored in a variable, that's it  they cannot change. Immutable variables are safer, produce no side effects, and lead to fewer bugs as a consequence.

In this recipe, we will create a small toy program that will declare variables in the three different ways that Dart allows  var, final, and const

Getting ready

Install the following before you get started with this recipe:

  • DartPad:
    1. In your browser, navigate to https://dartpad.dartlang.org.
  • Visual Studio Code:
    1. Double-check that the DartCode plugin has been installed. If you followed the steps in the previous chapter, you should be good to go.
    2. Press Command + N to create a new file and save it as main.dart.
  • IntelliJ:
    1. Double-check that you have the Dart plugin installed.
    2. Select Create new project. The following dialog will appear, asking what language and configuration you want to use: 

    1. Pick Dart as your language and then select Console Application. This effectively runs the same commands as the command-line instructions but wraps everything in a nice GUI.
When working with the code samples in this book, it is strongly discouraged that you copy and paste them into your IDE. Instead, you should transcribe the samples manually. The act of writing code, not copying/pasting, will allow your brain to absorb the code and see how tools such as code completion and DartFmt make it easier for you to type code. If you copy and paste, you'll get a working program, but you will also learn nothing.

How to do it...

Let's get started with our first Dart project. We will start from a blank canvas:

  1. Open main.dart and delete everything. At this point, the file should be completely empty. Now, let's add the main function, which is the entry point for every Dart program:
main() {
variablePlayground();
}
  1. This code won't compile yet because we haven't defined that variablePlayground function. This function will be a hub for all the different examples in this recipe:
void variablePlayground() {
basicTypes();
untypedVariables();
typeInterpolation();
immutableVariables();
}

We added the void keyword in front of this function, which is the same as saying that this function returns nothing.

  1. Now, let's implement the first example. In this method, all these variables are mutable; they can change once they've been defined:
void basicTypes() {
int four = 4;
double pi = 3.14;
num someNumber = 24601;
bool yes = true;
bool no = false;
int nothing;

print(four);
print(pi);
print(someNumber);
print(yes);
print(no);
print(nothing == null);
}

The syntax for declaring a mutable variable should look very similar to other programming languages. First, you declare the type and then the name of the variable. You can optionally supply a value for the variable after the assignment operator. If you don't supply a value, that variable will be set to null.

  1. Dart has a special type called dynamic, which is a sort of "get out of jail free" card from the type system. You can annotate your variables with this keyword to imply that the variable can be anything. It is useful in some cases, but for the most part, it should be avoided:
void untypedVariables() {
dynamic something = 14.2;
print(something.runtimeType); //outputs 'double'
}
  1. Dart can also infer types with the var keyword. var is not the same as dynamic. Once a value has been assigned to the variable, Dart will remember the type and it cannot be changed later. The values, however, are still mutable:
void typeInterpolation() {
var anInteger = 15;
var aDouble = 27.6;
var aBoolean = false;

print(anInteger.runtimeType);
print(anInteger);

print(aDouble.runtimeType);
print(aDouble);

print(aBoolean.runtimeType);
print(aBoolean);
}
  1. Finally, we have our immutable variables. Dart has two keywords that can be used to indicate immutability  final and const

The main difference between final and const is that const must be determined at compile time; for example, you cannot have const containing DateTime.now() since the current date and time can only be determined at runtime, not at compile time. See the How it works... section of this recipe for more details.
  1. Add the following function to the main.dart file:
void immutableVariables() {
final int immutableInteger = 5;
final double immutableDouble = 0.015;

// Type annotation is optional
final interpolatedInteger = 10;
final interpolatedDouble = 72.8;

print(interpolatedInteger);
print(interpolatedDouble);

const aFullySealedVariable = true;
print(aFullySealedVariable);
}

How it works...

An assignment statement in Dart follows the same grammar as other languages in the C language family:

// (optional modifier) (optional type) variableName = value;
final String name = 'Donald'; //final modifier, String type

First, you can optionally declare a variable as either varfinal, or const, like so:

var animal = 'Duck';
final numValue = 42;
const isBoring = true;

These modifiers indicate whether the variable is mutable. var is completely mutable as its value can be reassigned at any point. final variables can only be assigned once, but by using objects, you can change the value of its fields. const variables are compile-time constants and are fully immutable; nothing about these variables can be changed once they've been assigned.

Please note that you can only specify a type when you're using the final modifier, as follows:

final int numValue = 42; // this is ok
// NOT OK: const int or var int.

After the final modifier, you can optionally declare the variable type, from simple built-in types such as int, double, and bool, to your own more complex custom types. This notation is standard for languages such as Java, C, C++, Objective-C, and C#.

Explicitly annotating the type of a variable is the traditional way of declaring variables in languages such as Java and C, but Dart can also interpolate the type based on its assignment. In the typeInterpolation example, we decorated the types with the var keyword; Dart was able to figure out the type based on the value that was assigned to the variable. For example, 15 is an integer, while 27.6 is a double. In most cases, there is no need to explicitly reference the type; the compiler is smart enough to figure this out. This allows us, as developers, to write succinct, script-like code and still take advantage of inherent gains that we get from a type-safe language.

The difference between final and const is subtle but important. A final variable must have a value assigned to it in the same statement where it was declared, and that variable cannot be reassigned to a different value:

final meaningOfLife = 42;
meaningOfLife = 64; // This will throw an error

While the top-level value of a final variable cannot change, its internal contents can. In a list of numbers that have been assigned to a final variable, you can change the internal values of that list, but you cannot assign a completely new list.

const takes this one step further. const values must be determined at compile time, new values are blocked from being assigned to const variables, and the internal contents of that variable must also be completely sealed. Typically, this is indicated by having the object have a const constructor, which only allows immutable values to be used. Since their value is already determined at compile time, const values also tend to be faster than variables.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Work through practical recipes for building mobile applications with Flutter
  • Quickly build and iterate on your user interface (UI) with hot reload
  • Fix bugs and prevent them from reappearing using Flutter's developer tools and test suites

Description

“Anyone interested in developing Flutter applications for Android or iOS should have a copy of this book on their desk.” – Amazon 5* Review Lauded as the ‘Flutter bible’ for new and experienced mobile app developers, this recipe-based guide will teach you the best practices for robust app development, as well as how to solve cross-platform development issues. From setting up and customizing your development environment to error handling and debugging, The Flutter Cookbook covers the how-tos as well as the principles behind them. As you progress, the recipes in this book will get you up to speed with the main tasks involved in app development, such as user interface and user experience (UI/UX) design, API design, and creating animations. Later chapters will focus on routing, retrieving data from web services, and persisting data locally. A dedicated section also covers 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 also 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 be writing and delivering fully functional apps with confidence.

Who is this book for?

If you’re familiar with the basic concepts of programming and have your eyes set on developing mobile apps using Dart, then this book is for you. As a beginner, you’ll benefit from the clear and concise step-by-step recipes, while a more experienced programmer will learn best practices and find useful tips. You’ll get the most out of this book if you have experience coding in either JavaScript, Swift, Kotlin, Java, Objective-C, or C#.

What you will learn

  • Use Dart programming to customize your Flutter applications
  • Discover how to develop and think like a Dart programmer
  • Leverage Firebase Machine Learning capabilities to create intelligent apps
  • Create reusable architecture that can be applied to any type of app
  • Use web services and persist data locally
  • Debug and solve problems before users can see them
  • Use asynchronous programming with Future and Stream
  • Manage the app state with Streams and the BLoC pattern

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jun 18, 2021
Length: 646 pages
Edition : 1st
Language : English
ISBN-13 : 9781838827373
Category :
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jun 18, 2021
Length: 646 pages
Edition : 1st
Language : English
ISBN-13 : 9781838827373
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 106.97
Flutter Cookbook
€36.99
Flutter for Beginners
€44.99
Flutter Projects
€24.99
Total 106.97 Stars icon

Table of Contents

16 Chapters
Getting Started with Flutter Chevron down icon Chevron up icon
Dart: A Language You Already Know Chevron down icon Chevron up icon
Introduction to Widgets Chevron down icon Chevron up icon
Mastering Layout and Taming the Widget Tree Chevron down icon Chevron up icon
Adding Interactivity and Navigation to Your App Chevron down icon Chevron up icon
Basic State Management Chevron down icon Chevron up icon
The Future is Now: Introduction to Asynchronous Programming Chevron down icon Chevron up icon
Data Persistence and Communicating with the Internet Chevron down icon Chevron up icon
Advanced State Management with Streams Chevron down icon Chevron up icon
Using Flutter Packages Chevron down icon Chevron up icon
Adding Animations to Your App Chevron down icon Chevron up icon
Using Firebase Chevron down icon Chevron up icon
Machine Learning with Firebase ML Kit Chevron down icon Chevron up icon
Distributing Your Mobile App Chevron down icon Chevron up icon
Flutter Web and Desktop Chevron down icon Chevron up icon
About Packt Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2
(16 Ratings)
5 star 62.5%
4 star 18.8%
3 star 0%
2 star 12.5%
1 star 6.3%
Filter icon Filter
Top Reviews

Filter reviews by




ADITYA Aug 09, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
One of the best resource for anything looking and learn flutter as well as sharpen their skills. Everything is intuitive and easy to understand. I highly recommend this book to beginners and also to experienced individuals
Amazon Verified review Amazon
Rachana Sep 21, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Highly recommended book for flutter users The book is updated and the very latest version. It covers everything, its one of the first full fledged book that covers each and everything in detail. Its for anyone who has just started flutter and is looking for guide form basics.
Amazon Verified review Amazon
paulsm Oct 24, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Anyone interested in developing Flutter applications for Android or iOS should have a copy of this book on their desk. It has 100s of great examples. But more importantly, the authors explain the "whys" for behind each of the features they discuss. The materials are completely up-to-date. The audience is everybody from a "beginner" to "experienced developers": the only prerequisite is having some familiarity with at least one object-oriented programming language (like C#, Java or Python, among others).If you're interested in Flutter - or even if you've already developed a few Flutter apps - I can't recommend this book highly enough.
Amazon Verified review Amazon
Antonio Aguilar Nov 04, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book isn't like many of your "cookbook" style programming books which assume some level of understanding of the programming language. This books is designed for beginners who don't know any dart/flutter, and teaches you with robust code examples (unlike many books that only show you a snippet and expect you to follow along somehow without the greater context). That makes it pretty thick as half or more of the pages are just code, but it's worth the bulk for sure. At almost half way through I've found a few minor errors in the code but overall this book is one of the best I've read for learning a new language.
Amazon Verified review Amazon
abby1999 Aug 17, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I can wholeheartedly recommend this book to anyone wanting to pick up not JUST Flutter, but also the fundamentals of dart, working with Firebase, MLKit, and SO much more.What really impresses me is that Simone has even taken time to go deep into software architecture and design fundamentals (model view patterns, proper state management and so on), and personalized it to the Flutter/Dart paradigm. He covers everything from setting the Flutter kit up on your PC, to deploying Flutter apps, packages, websites and more.The bottom line is, if you're looking for a one stop solution for all your Flutter learning needs, THIS IS IT.Thanks for the amazing work put into this, Simone, and everyone else who contributed to it.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.