32,39 €
Are you ready to tap into the immense potential of Flutter?
With over 1,000 new mobile apps published every day on the Apple and Google Play stores, Flutter is transforming the landscape of app development. It's time for you to join the revolution.
Introducing the second edition of Flutter Cookbook, a step-by-step guide designed exclusively for you. Whether you're a seasoned developer or just starting your coding journey, this book is your ultimate companion. Dive into the latest features of Flutter 3.10 and unlock the secrets to building professional-grade, cross-platform applications.
With our recipe-based approach, we'll not only show you how to implement Flutter's features but also explain why they work. Through practical examples and real-world execution, you'll gain a deeper understanding of Flutter's inner workings. From crafting stunning UI/UX with widgets to leveraging hot reload and restart techniques, we'll equip you with best practices and invaluable knowledge.
As you progress, you'll learn to efficiently manage data, add interactivity and animations, and integrate essential Flutter plugins like maps, camera, voice recognition and more. And let's not forget the dedicated chapter on implementing MLkit powered by TensorFlow Lite. We'll guide you through building custom machine learning solutions, expanding the capabilities of your apps.
By the time you reach the end of this comprehensive Flutter book, you'll have the skills and confidence to write and deliver fully functional apps.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 658
Veröffentlichungsjahr: 2023
Flutter Cookbook
Second Edition
100+ step-by-step recipes for building cross-platform, professional-grade apps with Flutter 3.10.x and Dart 3.x
Simone Alessandria
BIRMINGHAM—MUMBAI
Flutter Cookbook
Second Edition
Copyright © 2023 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Senior Publishing Product Manager: Manish Nainani
Acquisition Editor – Peer Reviews: Gaurav Gavas
Project Editor: Meenakshi Vijay
Content Development Editor: Grey Murtagh
Assistant Editor: Elliot Dallow
Copy Editor: Safis Editing
Technical Editor: Srishty Bhardwaj
Proofreader: Safis Editing
Indexer: Manju Arasan
Presentation Designer: Rajesh Shrisath
Developer Relations Marketing Executive: Sohini Ghosh
First published: June 2021
Second edition: May 2023
Production reference: 1240523
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-80324-543-0
www.packt.com
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. 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 courses on Pluralsight, Udemy, and Kodeco.
I would like to thank the most phenomenal review team of all time! You were right more often than I would have preferred, but your contribution was truly invaluable.
As always, I’m grateful to my wife: Giusy, you rock!
Anna Leushchenko is a mobile development expert from Ukraine with over a decade of hands-on experience in creating quality software. Since obtaining her Master’s degree in Computer Science, she has brought numerous digital solutions to life, starting from sketches on a napkin and delivering functional and beautiful products to happy end-users. Anna is passionate about creating quality software, and programming is her major hobby.
Anna is a Google Developer Expert in Dart and Flutter, and a member of the Women Techmakers Ambassadors program, which attests to her high level of expertise and deep commitment to the community. She actively contributes to the tech industry by sharing top-notch quality deep dives into cross-platform mobile development topics at international tech conferences and is also recognized for her articles, which provide insights into creating quality software. Additionally, Anna participates in various community programs that focus on knowledge-sharing and mentors aspiring technologists to help them grow in their careers.
Oleksandr Leushchenko is a seasoned software developer with over a decade of experience in the industry. He is a Google Developer Expert in Flutter and Dart. His expertise spans various mobile platforms, having worked with Marmalade and Xamarin before transitioning to Flutter. Oleksandr holds a master’s degree in geographic information systems.
Throughout his career, Oleksandr has taken on numerous roles, including developer, technical leader, and head of the mobile stack. He, has worked in various domains, including healthcare, government, social networks, games, and mixed reality. He is currently working with a team of more than 40 Flutter engineers to create the best mobile banking app in the world.
Oleksandr has made significant contributions to the mobile development community through public speeches, articles and open source contributions.
AnnaandOleksandrwould like to express their heartfelt gratitude to the Armed Forces of Ukraine, selfless volunteers, and all those who tirelessly protect the independence and freedom of Ukraine.
A special thanks to Christian Mora, Pavan Kumar Reddy Venuthurla, and Luigi Micco for reading and providing feedback on the book to enhance the content further. Your help is much appreciated!
Preface
Who this book is for
What this book covers
To get the most out of this book
Get in touch
Getting Started with Flutter
Why Flutter?
Technical requirements
Installing Flutter: a high-level overview
Installing the Flutter SDK
How to use Git to manage the Flutter SDK
Installing Git
How to do it...
Setting up the command line and saving path variables
macOS command-line setup
Windows command-line setup
Linux command-line setup
Confirming your environment is correct with Flutter Doctor
Configuring the iOS SDK
Downloading Xcode
CocoaPods
Xcode command-line tools
Homebrew
Checking in with the Doctor
Configuring the Android SDK setup
Installing Android Studio
Creating an Android emulator
Which IDE/editor should you choose?
Android Studio
VS Code
IntelliJ IDEA
Emacs
Picking the right channel
Summary
Creating Your First Flutter App
How to create a Flutter app
How to do it...
How to choose a platform language for your app
Where do you place your code?
Hot reload—refresh your app without recompiling
Creating a unit test
Getting ready
How to do it...
How it works...
See also
Summary
Dart: A Language You Already Know
Technical requirements
Declaring variables—var versus final versus const
Getting ready
How to do it...
How it works...
There’s more...
See also
Strings and string interpolation
Getting ready
How to do it...
How it works...
There’s more...
See also
How to write functions
Getting ready
How to do it...
How it works...
How to use functions as variables with closures
Getting ready
How to do it...
How it works...
Using Switch Expressions, Records and Patterns
Getting ready
How to do it...
How it works…
There’s more...
Creating classes and using the class constructor shorthand
Getting ready
How to do it...
How it works...
The building blocks of OOP
See also
How to group and manipulate data with collections
Getting ready
How to do it...
How it works...
Subscript syntax
There’s more...
See also
Writing less code with higher-order functions
Getting ready
How to do it...
How it works...
Mapping
Sorting
Filtering
Reducing
Flattening
There’s more...
First-class functions
Iterables and chaining higher-order functions
See also
How to take advantage of the cascade operator
Getting ready
How to do it...
How it works...
See also
Using extensions
Getting ready
How to do it...
How it works...
Introducing Dart Null Safety
Getting ready
How to do it...
How it works...
See also
Using Null Safety in classes
Getting ready
How to do it...
How it works...
See also
Summary
Introduction to Widgets
Technical requirements
Creating immutable widgets
How to do it...
How it works...
Using a Scaffold
Getting ready
How to do it...
How it works...
Using the Container widget
Getting ready
How to do it...
How it works...
Printing stylish text on the screen
Getting ready
How to do it...
How it works...
There’s more...
See also
Importing fonts and images into your app
Getting ready
How to do it...
How it works...
See also
Summary
Mastering Layout and Taming the Widget Tree
Placing widgets one after another
Getting ready
How to do it...
How it works...
Proportional spacing with the Flexible and Expanded widgets
Getting ready
How to do it...
How it works...
See also
Drawing shapes with CustomPaint
Getting ready
How to do it...
How it works...
There’s more...
See also
Nesting complex widget trees
Getting ready
How to do it...
How it works...
See also
Refactoring widget trees to improve legibility
Getting ready
How to do it...
How it works...
See also
Applying global themes
Getting ready
How to do it...
How it works...
There’s more...
See also
Summary
Adding Interactivity and Navigation to Your App
Adding state to your app
Getting ready
How to do it...
How it works...
There’s more...
See also
Interacting with buttons
Getting ready
How to do it...
How it works...
Making it scroll
Getting ready
How to do it...
How it works...
There’s more...
Handling large datasets with list builders
How to do it...
How it works...
There’s more...
Working with TextFields
Getting ready
How to do it...
How it works...
See also
Navigating to the next screen
How to do it...
How it works...
Showing dialogs on the screen
Getting ready
How to do it...
How it works...
There’s more...
Presenting bottom sheets
Getting ready
How to do it...
How it works...
See also
Summary
Basic State Management
Technical requirements
Model-view separation
Getting ready
How to do it...
How it works...
See also
Managing the data layer with InheritedWidget and InheritedNotifier
Getting ready
How to do it...
How it works...
See also
Making the app state visible across multiple screens
Getting ready
How to do it...
How it works...
See also
Summary
The Future is Now: Introduction to Asynchronous Programming
Technical requirements
Using a Future
Getting ready
How to do it...
How it works...
See also
Using async/await to avoid callbacks
Getting ready
How to do it...
How it works...
See also
Completing Futures
Getting ready
How to do it...
How it works...
There’s more...
See also
Firing multiple Futures at the same time
Getting ready
How to do it...
How it works...
Resolving errors in asynchronous code
Getting ready
How to do it...
Dealing with errors using the then() callback:
Dealing with errors using async/await
How it works...
See also
Using Futures with StatefulWidgets
Getting ready
How to do it...
How it works...
There’s more...
See also
Using the FutureBuilder to let Flutter manage your Futures
Getting ready
How to do it...
How it works...
There’s more...
See also
Turning navigation routes into asynchronous functions
Getting ready
How to do it...
How it works...
Getting the results from a dialog
Getting ready
How to do it...
How it works...
See also
Summary
Data Persistence and Communicating with the Internet
Technical requirements
Converting Dart models into JSON
Getting ready
How to do it...
How it works...
Reading the JSON file
Transforming the JSON string into a list of Map objects
Transforming the Map objects into Pizza objects
There’s more...
See also
Handling JSON schemas that are incompatible with your models
Getting ready
How to do it...
How it works...
See also
Catching common JSON errors
Getting ready
How to do it...
How it works...
See also
Saving data simply with SharedPreferences
Getting ready
How to do it...
How it works...
See also
Accessing the filesystem, part 1: path_provider
Getting ready
How to do it...
How it works...
See also
Accessing the filesystem, part 2: Working with directories
Getting ready
How to do it...
How it works...
See also
Using secure storage to store data
Getting ready
How to do it...
How it works...
See also
Designing an HTTP client and getting data
Getting ready
How to do it...
How it works...
There’s more...
See also
POST-ing data
Getting ready
How to do it...
How it works...
PUT-ting data
Getting ready
How to do it...
How it works...
DELETE-ing data
Getting ready
How to do it...
How it works...
Advanced State Management with Streams
Technical requirements
How to use Dart streams
Getting ready
How to do it...
How it works...
There’s more...
See also
Using stream controllers and sinks
Getting ready
How to do it...
How it works...
There’s more...
See also
Injecting data transforms into streams
Getting ready
How to do it...
How it works...
See also
Subscribing to stream events
Getting ready
How to do it...
How it works...
See also
Allowing multiple stream subscriptions
Getting ready
How to do it...
How it works...
See also
Using StreamBuilder to create reactive user interfaces
Getting ready
How to do it...
How it works...
See also
Using the BLoC pattern
Getting ready
How to do it...
How it works...
See also
Summary
Using Flutter Packages
Technical requirements
Importing packages and dependencies
Getting ready
How to do it...
How it works...
See also
Using dev dependencies
Getting ready
How to do it...
How it works...
See also
Creating your own package (part 1)
Getting ready
How to do it...
How it works...
See also
Creating your own package (part 2)
Getting ready
How to do it...
How it works...
See also
Creating your own package (part 3)
Getting ready
How to do it...
How it works...
See also
Adding Google Maps to your app
Getting ready
How to do it...
Adding Google Maps on Android
Adding Google Maps on iOS
How it works...
See also
Using location services
Getting ready
How to do it...
How it works...
See also
Adding markers to a map
Getting ready
How to do it...
How it works...
There’s more...
Summary
Adding Animations to Your App
Creating basic container animations
Getting ready
How to do it...
How it works...
See also
Designing animations part 1 — Using the AnimationController
Getting ready
How to do it...
How it works...
See also
Designing animations part 2 — Adding multiple animations
Getting ready
How to do it…
How it works...
Designing animations part 3 — Using curves
Getting ready
How to do it...
How it works...
See also
Optimizing animations
Getting ready
How to do it...
How it works...
See also
Using Hero animations
Getting ready
How to do it...
How it works...
See also
Using premade animation transitions
Getting ready
How to do it...
How it works...
See also
Using the AnimatedList widget
Getting ready
How to do it...
How it works...
See also
Implementing swiping with the Dismissible widget
Getting ready
How to do it...
How it works...
See also
Using the animations Flutter package
Getting ready
How to do it...
How it works...
See also
Summary
Using Firebase
Configuring a Firebase app
Getting ready
How to do it...
Adding Firebase dependencies
How it works...
See also
Creating a login screen
Getting ready
How to do it...
How it works...
See also
Adding Google Sign-in
Getting ready
How to do it...
How it works...
See also
Customizing Sign in
Getting ready
How to do it...
How it works...
Integrating Firebase Analytics
Getting ready
How it works...
How it works...
See also
Using Firebase Cloud Firestore
Getting ready
How to do it...
How it works...
See also
Sending push notifications with Firebase Cloud Messaging (FCM)
Getting ready
How to do it...
How it works...
See also
Storing files in the cloud
Getting ready
How to do it...
How it works...
Summary
Firebase Machine Learning
Using the device’s camera
Getting ready
How to do it...
How it works...
See also
Recognizing text from an image
Getting ready
How to do it...
How it works...
See also
Reading a barcode
Getting ready
How to do it...
How it works...
See also
Image labeling
Getting ready
How to do it...
How it works...
Building a face detector and detecting facial gestures
Getting ready
How to do it...
How it works...
See also
Identifying a language
Getting ready
How to do it...
How it works...
See also
Using TensorFlow Lite
Getting ready
How to do it...
How it works...
See also
Summary
Flutter Web and Desktop
Creating a responsive app leveraging Flutter Web
Getting ready
How to do it...
How it works...
See also...
Running your app on macOS
Getting ready
How to do it...
How it works...
See also
Running your app on Windows
Getting ready
How to do it...
How it works...
See also...
Deploying a Flutter website
Getting ready
How to do it...
How it works...
See also...
Responding to mouse events in Flutter Desktop
Getting ready
How to do it…
How it works...
See also
Interacting with desktop menus
Getting ready
How to do it...
How it works...
See also...
Summary
Distributing Your Mobile App
Technical requirements
Registering your iOS app on App Store Connect
Getting ready
How to do it...
How it works...
See also
Registering your Android app on Google Play
Getting ready
How to do it...
How it works...
See also
Installing and configuring fastlane
Getting ready
How to do it...
Installing fastlane on Windows
Installing fastlane on a Mac
Configuring fastlane for Android
Installing fastlane for iOS
See also
Generating iOS code signing certificates and provisioning profiles
Getting ready
How to do it...
How it works...
See also
Generating Android release certificates
Getting ready
How to do it...
How it works...
See also
Configuring your app metadata
Getting ready
How to do it...
Adding Android metadata
Adding metadata for iOS
How it works...
See also
Adding icons to your app
Getting ready
How to do it...
How it works...
See also
Publishing a beta version of your app in the Google Play Store
Getting ready
How to do it...
How it works...
See also
Using TestFlight to publish a beta version of your iOS app
Getting ready
How to do it...
How it works...
See also
Publishing your app to the stores
Getting ready
How to do it...
Moving your app to production in the Play Store
Moving your app to production in the App Store
How it works...
See also
Summary
Other Books You May Enjoy
Index
Cover
Index
These recipes cover the most important Flutter features that will allow you to develop real-world apps. In each recipe, you will learn about and immediately use some of the tools that make Flutter so successful: widgets, state management, asynchronous programming, connecting to web services, persisting data, creating animations, using Firebase and machine learning, and developing responsive apps that work on different platforms, including desktop and the web.
Flutter is a developer-friendly, open source toolkit created by Google that you can use to create applications for Android and iOS mobile devices, the web, and desktop.
There are 16 chapters in this book, which you can read independently from one another: each chapter contains recipes that highlight and leverage a single Flutter feature. You can choose to follow the flow of the book or skip to any chapter if you feel confident with the concepts.
Flutter uses Dart as a programming language. Chapter 3, Dart: A Language You Already Know, is an introduction to Dart, its syntax, and its patterns, and it gives you the necessary knowledge to be productive when using Dart in Flutter.
In later chapters, you’ll see recipes that go beyond basic examples; you will be able to play with code and get hands-on experience in using basic, intermediate, and advanced Flutter tools.
This book is for developers who are familiar with an object-oriented programming language. If you understand concepts such as variables, functions, classes, and objects, this book is for you.
Prior knowledge of Dart is not required as it is introduced in Chapter 3, Dart: A Language You Already Know.
If you already know and use languages such as Java, C#, Swift, Kotlin, and JavaScript, you will find Dart surprisingly easy to learn.
Chapter 1, Getting Started with Flutter, helps you set up your development environment.
Chapter 2, Creating Your First Flutter App, shows how to create your first app, and check that your development environment works as expected.
Chapter 3, Dart: A Language You Already Know, introduces Dart, its syntax, and its patterns.
Chapter 4, Introduction to Widgets, shows how to build simple user interfaces with Flutter.
Chapter 5, Mastering Layout and Taming the Widget Tree, shows how to build more complex screens made of several widgets.
Chapter 6, Adding Interactivity and Navigation to Your app, contains several recipes that add interactivity to your apps, including interacting with buttons, reading a text from a TextField, changing the screen, and showing alerts.
Chapter 7, Basic State Management, introduces the concept of State in Flutter: instead of having screens that just show widgets, you will learn how to build screens that can keep and manage data.
Chapter 8, The Future is Now: Introduction to Asynchronous Programming, contains several examples of one of the most useful and interesting features in programming languages: the concept of the asynchronous execution of tasks.
Chapter 9, Data Persistence and Communicating with the Internet, gives you the tools to connect to web services and persist data on your device.
Chapter 10, Advanced State Management with Streams, shows how to deal with Streams, which are arguably the best tool for creating reactive apps.
Chapter 11, Using Flutter Packages, explains how to choose, use, build, and publish Flutter packages.
Chapter 12, Adding Animations to Your app, gives you the tools you need to build engaging animations in your apps.
Chapter 13, Using Firebase, shows how to leverage a powerful backend without any code.
Chapter 14, Firebase Machine Learning, shows how to add machine learning features to your apps by using Firebase.
Chapter 15, Flutter Web and Desktop, shows you how to use the same code base to build apps for the web and desktop.
Chapter 16,Distributing Your Mobile app, outlines the steps required to publish an app to the main mobile stores: the Google Play Store and the Apple App Store.
Some experience in at least one object-oriented programming language is strongly recommended.
In order to follow along with the code, you will need a Windows PC, Mac, Linux, or Chrome OS machine connected to the web, with at least 8 GB of RAM and the permissions to install new software.
An Android or iOS device is suggested but not necessary as there are simulators/emulators that can run on your machine. All software used in this book is open source or free to use.
Chapter 1, Getting Started with Flutter, explains in detail the installation process; however, you should have the following:
Software/hardware
OS Requirements
Recommended editors: Visual Studio Code, Android Studio, or IntelliJ Idea
Windows, macOS, or Linux
The Flutter SDK
Windows, macOS, or Linux
An emulator/simulator or an iOS or Android device
Windows, macOS, or Linux
In order to create apps for iOS, you will need a Mac.
If you are using the digital version of this book, we advise you to type the code yourself or access the code via the GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.
If you like this book or want to share your ideas about it, please write a review on your favorite platform. This will help us make this book better, and you’ll also earn the author’s and reviewers’ everlasting gratitude.
The code bundle for the book is hosted on GitHub at https://github.com/PacktPublishing/Flutter-Cookbook-Second-Edition/. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://packt.link/WE615.
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. For example: “Add the latest version of the lint package as a dev dependency in your pubspec.yaml, and remove any other linting packages you may find there.”
A block of code is set as follows:
dependencies:flutter:sdk:flutterhttp:^0.13.5When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
dev_dependencies:flutter_test:sdk:flutterlint:^2.0.0Any command-line input or output is written as follows:
# cp /usr/src/asterisk-addons/configs/cdr_mysql.conf.sample /etc/asterisk/cdr_mysql.confBold: Indicates a new term, an important word, or words that you see on the screen. For instance, words in menus or dialog boxes appear in the text like this. For example: “ In order to use Google Maps, you need to obtain an API key.”
Warnings or important notes appear like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book’s title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you reported this to us. Please visit http://www.packtpub.com/submit-errata, click Submit Errata, and fill in the form.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit http://authors.packtpub.com.
Once you’ve read Flutter Cookbook, Second Edition, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.
Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.
Thanks for purchasing this book!
Do you like to read on the go but are unable to carry your print books everywhere?Is your eBook purchase not compatible with the device of your choice?
Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.
Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.
The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily
Follow these simple steps to get the benefits:
Scan the QR code or visit the link belowhttps://packt.link/free-ebook/9781803245430
Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directlyWhenever you begin developing with a new platform, the first task you need to perform is creating your development environment. In some ways, the ease with which you can go from nothing to building the first “hello world” app can be seen as a test for how your experience with the new platform is going to be. If the environment is difficult and painful to set up, then it may be very likely that it will be difficult and painful to work with.
By the end of this chapter, you will have Flutter fully installed and will be ready to run your first app.
In this chapter, we’ll be covering the following topics:
Why Flutter?Technical requirementsInstalling Flutter: a high-level overviewHow to use Git to manage the Flutter SDKSetting up the command line and saving path variables Using Flutter doctor to diagnose your environmentConfiguring the iOS SDKSetting up CocoaPods (iOS only)Configuring the Android SDK setupWhich IDE/editor should you choose?Picking the right channelHow to choose the platform language for your appLet’s begin by discussing why Flutter may be a great framework to work with.
Flutter is an open-source framework to build apps, created by Google. Before investing time and effort in learning a new framework, there is a critical question we need to answer: Is Flutter worth learning and using?
While the answer to this question probably depends on your needs and expectations, there are several reasons that make Flutter a great framework to learn and use. Some of them include:
Cross-platform: With Flutter, you can build apps for iOS and Android, web, desktop, and IoT devices with a single code base.Fast development: Flutter includes several features that help speed up your development workflow. Among the most important, it’s worth mentioning hot reload, hot restart, and sound null safety support.User interface: Flutter provides a rich set of widgets to create beautiful, high-performance apps.Open source: Flutter and Dart (the programming language you use in Flutter) are open source and supported by Google.Community: Flutter has a large and active community. This means you can easily find great resources, third-party packages, and help.Performance: Flutter uses a reactive programming model and a high-performance rendering engine, and compiles to native code.There are arguably other points we could add here, but hopefully, you’ll discover several more yourself while reading this book.
Flutter requires a 64-bit operating system. In particular:
For Windows, you will need Windows 10 or later (64-bit and x86-64 based), Git for Windows, and PowerShell 5 or newer.For macOS, OS X Yosemite 10.10 or later is required.For Linux and ChromeOS, there is a list of common programs that should be installed in your system before setting up Flutter. More info can be found here: https://docs.flutter.dev/get-started/install/linux (for Linux) and here: https://docs.flutter.dev/get-started/install/chromeos (for ChromeOS).Building mobile applications can be a taxing task for your computer. While the minimum hardware requirements to develop a Flutter app are relatively low, your developing experience will be greatly enhanced with the following specs:
8 GB of random-access memory (RAM). 16 gigabytes (GB) is preferred, especially when using a virtual device (emulator or simulator).At least 50 GB of available hard drive space.A solid-state drive (SSD) hard drive. At least a 2 gigahertz (GHz) processor.A reliable internet connection.If you want to build for iOS, you will need a Mac.Flutter itself doesn’t have strict hardware requirements, but anything less than this may lead to you spending more time waiting rather than working.
Let’s see how to install your Flutter development environment next.
You can start developing Flutter apps without any installation or configuration. You can quickly create prototypes and simple apps and share your code with fellow developers with an online tool called DartPad, available here: https://dartpad.dev. It is an online open-source tool that runs on any browser.
However, if you are serious about programming with Flutter, there will come a time when you need to develop your apps locally and, therefore, will need to configure your system.
Configuring your Flutter development environment is rather easy. You can divide the process into three parts:
First, you must install the Flutter software development kit (SDK). Currently, you can build Flutter apps from Windows, macOS, Linux, and ChromeOS.Then, depending on your target platform, you have to install a specific platform SDK: Android, iOS, and/or desktop. You can also develop for the web, without installing any specific SDK. Note that:Any supported device can build apps for Android and the web.You can build iOS apps only from a Mac.You can only build desktop apps when the origin and target are the same: a Windows app can only be built from a Windows desktop, a macOS app only from a macOS desktop, etc.The final stage is choosing which editor, or integrated development environment (IDE), you want to use.To make this process even easier, Flutter has a tool called Flutter Doctor, which will scan your environment and offer you step-by-step guides for what you need to do to successfully complete your environment setup.
Before you can build anything, you need to download the Flutter SDK.
On the main Flutter website at https://docs.flutter.dev/get-started/install, you’ll find the prebuilt packages for Windows, macOS, Linux, or ChromeOS—the currently supported platforms to create Flutter apps.
Figure 1.1: The Flutter installation page
Once you select your operating system, whatever your choice, you will find a section called Get the Flutter SDK. Here, you will find a compressed file (.zip for Windows and macOS, and .tar.gz for Linux and ChromeOS).
You should then create a directory for the Flutter SDK, and extract the contents of the compressed file into that directory; for instance, this could be c:\dev\flutter on a Windows machine or ~/development on other platforms.
There is another tool, called FVM (Flutter Version Management), that allows managing multiple versions of Flutter SDKs on your development machine.
If you install it, you can switch between different versions of Flutter, without having to manually download and install each version. This is very useful when you work on projects that require different versions of Flutter.
You’ll find FVM here: https://fvm.app/docs/getting_started/installation/.
An alternative way to install the Flutter SDK is using Git.
Since Flutter is open source and hosted on GitHub, if you clone the main Flutter repository, you’ll already have everything you need. As an added bonus, you can easily change to different versions of the Flutter SDK when needed.
The packages that are available to download on Flutter’s website are snapshots from the Git repository. Flutter uses Git internally to manage its versions, channels, and upgrades.
First, you need to make sure you have Git installed on your computer. Git is installed by default on most Mac and Linux machines. For Windows, you can download and install Git here: https://git-scm.com/download/win.
You can also download a Git client to make working with repositories a bit easier. Tools such as Sourcetree (https://www.sourcetreeapp.com) or GitHub Desktop (https://desktop.github.com) can simplify working with Git. They are optional, however, and this book will stick to the command line when referencing Git.
To confirm that Git is installed on Linux and macOS, open your Terminal and type which git. You should see a /usr/bin/git path returned. If you see nothing, then Git is not installed correctly: you may follow the instructions at https://git-scm.com/book/en/v2/Getting-Started-Installing-Git and try to repeat the installation process to solve installation issues.
On all platforms, from your Terminal or Command Prompt, you can type the following command: git –version. You’ll then see the current Git version installed in your system.
Follow these steps to clone and configure the Flutter SDK:
First, choose a directory where Flutter is going to be installed. The specific location does not matter, but make sure you have permissions to read, write, and execute in your chosen location.On Windows, you might choose a folder called c:\development\flutter. In this case, in your Command Prompt, type: cd\development\flutter On macOS, to install Flutter in the $HOME directory, from your Terminal, type in the following command: cd $HOME Another common path on macOS is the ~ path; in this case, just type: cd ~ On Linux, you might choose a /flutter directory. In this case, just type: cd /flutter We can now install Flutter. From your Terminal, type the command: git clone https://github.com/flutter/flutter.gitThis will download Flutter and all of its associated tools, including the Dart SDK.
Now that you have installed the Flutter SDK, there are a few more steps needed to make the software accessible on your computer. Unlike apps with user interfaces (UIs), Flutter is primarily a command-line tool. Let’s quickly learn how to set up the command line on macOS, Windows, and Linux in the following sections.
To use Flutter on macOS, you need to save the location of the Flutter executable to your system’s environment variables.
Newer Macs use the Z shell (also known as zsh). This is basically an improved version of the older Bash, with several additional features.
When using zsh, you can add a line to your zshrc file, which is a text file that contains the zsh configuration. If the file does not exist yet, you can create a new file as follows:
Open the zshrc file with the following command in your Terminal: nano $HOME/.zshrc This will open a basic text editor called nano in your Terminal window. There are other popular tools, such as vim and emacs, that will also work.Type the following command at the bottom of the file: export PATH="$PATH:$HOME/flutter/bin"If you chose to install Flutter at a different location, then replace $HOME with the appropriate directory.
Exit nano by pressing Ctrl+ X. Don’t forget to save your file when prompted.Reload your Terminal session by typing the following command: source ~/.zshrc Finally, confirm that everything is configured correctly by typing the following: which flutterYou should see the directory where you cloned (or installed) the Flutter SDK printed on the screen, as shown in the following screenshot:
Figure 1.2: The result of the which flutter command on macOS Terminal
To use Flutter on Windows, you need to save the location of the Flutter executable to your system’s environment variables.
These instructions assume you are using Windows 10 or 11. The screenshots in this section are taken from a Windows 11 PC.
You will now set up your environment variables for Flutter on Windows:
Click on the Start button, and type env. You should see the System Properties dialog window.Figure 1.3: System Properties dialog window for Windows
At the bottom of the dialog, you will find an Environment Variables… button. Click on it.In the next dialog, select the Path variable in the User variables for sales section and click the Edit... button:Figure 1.4: The Environment Variables dialog window for Windows
Finally, add the location where you installed Flutter to your path:Figure 1.5: The Edit environment variable dialog window for Windows
Type C:\Users\{YOUR_USER_NAME}\flutter\bin, then select OK. Flutter should now be added to your path.Restart your system.Type flutter in the command line. You should see a message with some Flutter command-line interface (CLI) instructions. Flutter might optionally download more Windows-specific tools at this time.To use Flutter in Linux, you need to update the PATH variable in your system:
From your shell window, edit the $HOME/.bashrc file with your favorite editor.Add the following line to the file: export PATH="$PATH:[FLUTTER_PATH]/bin" Open a new Terminal window to automatically source the file. Type the following command: which flutterYou should see the directory where you cloned (or installed) the Flutter SDK printed on the screen.
In some cases, the instructions above may not work on your Linux distro. See the Update path directly section at https://docs.flutter.dev/get-started/install/linux#update-your-path.
Flutter comes with a tool called Flutter Doctor. This tool provides a list of everything that needs to be done to make sure that Flutter can run correctly. You are going to use Flutter Doctor as a guide during the installation process. This tool is also invaluable in checking whether your system is up to date.
In your Terminal window, type the following command:
flutter doctorFlutter Doctor will tell you whether your platform SDKs are configured properly and whether Flutter can see any devices, including physical mobile devices, simulators and emulators, your desktop, and the web browser.
The iOS SDK is provided by a single application: Xcode. Xcode is one behemoth of an application; it controls all the official ways in which you will interact with Apple’s platforms and is only available for macOS. As large as Xcode is, there are a few pieces of software that are missing. Two of these are community tools: CocoaPods and Homebrew. These are package managers, or programs that install other programs. You can use both of these tools to build iOS apps.
The iOS SDK comes bundled with Apple’s IDE, Xcode. The best place to get Xcode is through the Apple App Store:
Press Command + Space to open Spotlight and then type in app store:Figure 1.6: App Store results in Spotlight
As an alternative, you can just click on the menu in the top-left corner of your screen and select App Store, but keyboard shortcuts are much more fun.
After the App Store opens, search for Xcode and select Download:Figure 1.7: Xcode in the App Store
To see the full-color version of Figure 1.7, and all the other images in this book, download the PDF file here: https://packt.link/WE615.
Xcode is a rather large application, so it may take a while to download. While Xcode is installing, you can get some of the smaller tools that you’ll need for development. Let’s take a look at how to install these tools in the following sections.
CocoaPods is a popular community-led dependency manager for iOS development, both for Swift and Objective-C languages.
Basically, a dependency manager is a tool that helps you manage external libraries or packages required by your projects. When you write code, you sometimes need to use code written by other people or teams. A dependency manager automates the tasks to install, update, and delete these third-party packages.
In order to use some iOS-specific plugins in a Flutter app, it is recommended to install CocoaPods. This allows your app to access native libraries provided by iOS, required by certain plugins to function properly.
Flutter requires CocoaPods in its build process to link any libraries you have added to your project:
To install (or update) CocoaPods, type the following command in the Terminal: sudo gem install cocoapodsSince this command requires administrator privileges, you will likely be prompted to enter your password before continuing. This should be the same password that you use to log in to your computer.
This will configure your local version of the cocoapods repository, which can take some time.
CocoaPods can manage and install external libraries in a Flutter app that uses Objective-C or Swift code; it’s not strictly required to build Flutter apps, but adding libraries manually, while possible, would be more difficult and time-consuming.
Command-line tools are used by Flutter to build your apps without needing to open Xcode. They are an extra add-on that requires your primary installation of Xcode to be complete:
Verify that Xcode has finished downloading and has been installed correctly.After it is done, open the application to allow Xcode to fully configure itself.Once you see the Welcome to Xcode screen appear, you can close the application:Figure 1.8: Xcode Welcome screen
Type the following command in the Terminal window to install the command-line tools: sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer You may also need to accept the Xcode license agreement. Flutter Doctor will let you know if this step is required. You can either open Xcode and will be prompted to accept the agreement on the first launch, or you can accept it via the command line, with the following command: sudo xcodebuild -license acceptAfter completing these steps, you’ll be able to use the Xcode command-line tools without needing to open Xcode in your system.
Homebrew is a package manager used to install and manage applications on macOS. If CocoaPods manages packages that are specific to your project, then Homebrew manages packages that are global to your computer.
Homebrew can be installed with this command in your Terminal window:
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"We will be using Homebrew primarily as a mechanism to download and install other, smaller tools.
You can also find more information about Homebrew on its website: https://brew.sh.
Now that we have all the platform tools for iOS, let’s run Flutter Doctor one more time to make sure everything is installed correctly.
You may end up seeing this as a result:
Figure 1.9: Flutter Doctor error
Remember how earlier you installed Homebrew? It’s now going to come in handy. You now have two options to solve this problem: you can either copy/paste each one of these brew commands one by one into a Terminal window, or you can automate this with a single shell script.
The result will be the same, but let’s create a single shell script:
Select and copy all the brew commands in Step 2, then enter nano again with the following command: nano update_ios_toolchain.sh Add the following commands in the file and then save and exit nano: brew update brew uninstall --ignore-dependencies libimobiledevice brew uninstall --ignore-dependencies usbmuxd brew install --HEAD usbmuxd brew unlink usbmuxd brew link usbmuxd brew install --HEAD libimobiledevice brew install ideviceinstaller Run this script with the following command: sh update_ios_toolchain.sh To delete the script file after its execution, just type: rm update_ios_toolchain.sh When the script finishes, run flutter doctor one more time. Everything for the iOS side should now be green.Just like with Xcode, Android Studio and the Android SDK come hand in hand, which should make this process fairly easy. But also like Xcode, Android Studio is just the starting point. There are a bunch of tiny tools that you’ll need to get everything up and running.
Follow these steps to install Android Studio:
You can download Android Studio at https://developer.android.com/studio.The website will autodetect your operating system and only show the appropriate download link:
Figure 1.10: Android Studio download page
After Android Studio is installed, you’ll need to download your target Android SDK(s). From the Android Studio menu, select Preferences and then type android into the search field:
Figure 1.11: Android Studio SDKs screen
While it may be tempting to grab the most recent version of the Android SDK, you might want to choose the second most recent version, because the Flutter SDK is sometimes a bit behind Android. In most cases, it shouldn’t matter, but Android is notorious for breaking compatibility, so be aware of this.
If you ever need to change your version of the Android SDK, you can always uninstall and reinstall it from the screen in Figure 1.11
Figure 1.12: Android Studio Android SDK Tools screen
After everything finishes installing, run flutter doctor to check that everything is working as expected.In order to run your app, you are going to need some kind of device to run it on. When it comes to Android, nothing beats the real thing. If you have access to a real Android device, you can use that device for development. It will also be less resource-consuming for your system, as your PC or Mac won’t have to supply the RAM, processor, and disk of another device.
However, there are also advantages to using an Android emulator (and an iOS simulator).
When developing, it is often simpler to have a virtual device next to your code rather than having to carry around real devices with their required cables.
Follow these steps to set up your first emulator:
Select the Android Virtual Device Manager (AVD Manager) from the toolbar in Android Studio:Figure 1.13: Android Studio toolbar
The first time you open the AVD Manager, you’ll get a splash screen. Select the Create Virtual Device... button in the middle to start building your virtual device:Figure 1.14: Android Studio Android “Your Virtual Devices” screen
The next text screen allows you to configure which Android hardware you want to emulate. I recommend using a Pixel device (any version will do):Figure 1.15: Android Studio AVD Select Hardware screen
On the next screen, you will have to pull down an Android runtime. For the most part, the most recent image will be sufficient. Each one of these images is several GB in size, so only download what you need:Figure 1.16: Android Studio AVD System Image screen
Click Next to create your emulator. You can launch the emulator if you want, but this is not necessary.Once again, run flutter doctor to check your environment. One final thing that you may have to do is accept all the Android license agreements. You can do this quickly from the Terminal line with this command: flutter doctor –-android-licenses Keep typing y when prompted to accept all the licenses (I have a feeling you aren’t reading them anyway). Run flutter doctor one more time just for good measure. The Android SDK should now be fully configured.Congratulations! The Flutter SDK should now be fully set up for both iOS and Android. In the next recipes in this chapter, we are going to explore some optional choices to customize your environment to fit your needs.
A developer’s IDE is a very personal choice, and developers may engage in heated battles over the best tool to use.
Ultimately, the choice is dependent on which tool you are most productive and more capable in. If you find yourself fighting with the tool rather than just writing code, then it might not be the right choice. As with most things, it’s more important to make choices based on what best fits your personal and unique style, rather than follow any prescribed doctrine.
You can develop Flutter apps with any editor, including Notepad and the Flutter CLI, but Flutter provides official plugins for four popular IDEs:
Android Studio Visual Studio Code (VS Code)IntelliJ IDEAEmacsLet’s compare and configure all four and find out which one might be right for you.
Android Studio is a mature and stable IDE. Since 2014, Android Studio has been promoted as the default tool for developing Android applications. Before that, you would have had to use a variety of plugins for legacy tools such as Eclipse. One of the biggest arguments in favor of using Android Studio is that it’s the easiest way to install the Android SDK, so you probably already have it installed.
To add the Flutter plugin, select the Android Studio menu, then select Preferences:
Click on the Plugins tab to open the Plugins Marketplace. Search for Flutter and install the plugin. This will also install the Dart plugin. You will then be prompted to restart Android Studio:Figure 1.17: Android Studio Plugins screen
Android Studio is a very powerful tool. At the same time, the program can seem intimidating at first, with all the panels, windows, and too many options to enumerate. You will need to spend a few weeks with the program before it starts to feel natural and intuitive.
With all this power comes a consequence: Android Studio is a very demanding application. On a laptop, the IDE can drain your battery very quickly, so keep your power cable nearby. You should also make sure you have a relatively powerful computer; otherwise, you might spend more time waiting than writing code. See the hardware recommendations in the Technical requirements section at the beginning of this chapter for further details.
VS Code is a free, lightweight, highly extensible tool from Microsoft that can be configured for almost any programming language, including Flutter.
You can download VS Code from https://code.visualstudio.com.
After you’ve installed the application, click on the fifth button in the left sidebar to open the Extensions Marketplace. Search for flutter and then install the extension:
Figure 1.18: Visual Studio Code Flutter extension screen
This will also install the Dart plugin.
VS Code is much kinder on your hardware than Android Studio and has a wide array of community-written extensions. You will also notice that the UI is simpler than Android Studio, and your screen is not covered with panels and menus. This means that most of the features that you would see out in the open in Android Studio are accessible through keyboard shortcuts in VS Code.
Unlike Android Studio, most of the Flutter tools in VS Code are accessible through the Command Palette.
Press Ctrl + Shift + P on Windows or Command + Shift + P on a Mac to open the Command Palette and type >Flutter to see the available options. You can also access the Command Palette through the View menu:
Figure 1.19: VS Code Command Palette
If you want a lightweight but complete environment that you can customize to your needs, then VS Code is the right tool for you. This is my favorite editor when developing Flutter apps.
IntelliJ IDEA is another extremely powerful and flexible IDE. You can download the tool from this website: https://www.jetbrains.com/idea/. Currently, this is the only paid-for tool in this group.
If you look carefully, you’ll probably notice that IntelliJ IDEA looks very similar to Android Studio, and that is no coincidence. Android Studio is really just a modified version of IntelliJ IDEA. This also means that all the Flutter tools we installed for Android Studio are the exact same tools that are available for IntelliJ IDEA.
So, why would you ever want to use IntelliJ IDEA if you already have Android Studio? Android Studio has removed many of the features in IntelliJ IDEA that aren’t related to Android development. This means that if you are interested in web or server development, you can use IntelliJ IDEA to get the same experience.
Emacs is the latest addition to the officially supported editors for Flutter. You can download it from https://www.gnu.org/software/emacs/download.html.
After you’ve installed the application, you need to enable LSP (Language Server Protocol) mode. This makes sure the editor communicates with a server that contains information about any language. You’ll find information about the installation process at this link: https://emacs-lsp.github.io/lsp-mode/page/installation/.
Then, you need to install the lsp-dart package (https://emacs-lsp.github.io/lsp-dart/), which enables several great language tools you can leverage when using Flutter.
Emacs’ most interesting feature is probably that it is part of the GNU project. The goal of the GNU project is to provide a free software environment that can be modified and redistributed by anyone. This means that you can run, copy, distribute, modify, or change Emacs as you see fit. It also means that you are totally in control of how the software works under the hood.
Other than that, Emacs is extremely lightweight, more than any other editor in this list. On the other hand, it’s definitely less user-friendly and offers a more “minimalistic” experience when developing with Flutter, so I would recommend it only to developers who are already familiar with it.
One final item we need to cover before diving into building apps is the concept of channels. Flutter segments its development streams into channels, which is really just a fancy name for Git branches. Each channel represents a different level of stability for the Flutter framework. Flutter developers will release the latest features to the master channel first. As these features stabilize, they will get promoted to the beta channel, and then to the stable channel.
In previous Flutter versions, there was also a dev channel, between master and beta, but this was removed. The Flutter versioning policy will probably be updated in the near future, so please have a look at the Flutter build release page at https://github.com/flutter/flutter/wiki/Flutter-build-release-channels for the latest versioning updates.
Most of the time, you will probably want to stick to the stable channel. This will make sure that your code mostly runs without any issues. If you were interested in cutting-edge features that may not be completely finished, you’d probably be more interested in the master or beta channels.
In order to make sure you are using the stable channel:
In your Command Prompt or Terminal, type in the following command: flutter channel If you downloaded the Flutter pre-compiled SDK, you’ll probably see output that looks like this:If you chose to clone the Flutter repository with Git, it defaults to the master channel. You’ll generally want to stick to something more reliable.
Type in these commands: flutter channel stable flutter upgrade This will switch the Flutter SDK to the stable channel and then make sure that you are running the most recent version.You may have noticed references to Git when switching channels. This is because, under the hood, Flutter channel is just a fancy name for a Git branch. If you were so inclined, you could switch channels using the Git command line, but you might also desynchronize your Flutter tool. Make sure to always run flutter upgrade in your Terminal after switching channels/branches.
