Flutter for Beginners: An introductory guide to building cross-platform mobile applications with Flutter and Dart 2
()
About this ebook
A step-by-step guide to learning Flutter and Dart 2 for creating Android and iOS mobile applications
Key Features- Get up to speed with the basics of Dart programming and delve into Flutter development
- Understand native SDK and third-party libraries for building Android and iOS applications using Flutter
- Package and deploy your Flutter apps to achieve native-like performance
Google Flutter is a cross-platform mobile framework that makes it easy to write high-performance apps for Android and iOS. This book will help you get to grips with the basics of the Flutter framework and the Dart programming language.
Starting from setting up your development environment, you’ll learn to design the UI and add user input functions. You'll explore the navigator widget to manage app routes and learn to add transitions between screens. The book will even guide you through developing your own plugin and later, you’ll discover how to structure good plugin code. Using the Google Places API, you'll also understand how to display a map in the app and add markers and interactions to it. You’ll then learn to improve the user experience with features such as map integrations, platform-specific code with native languages, and personalized animation options for designing intuitive UIs.
The book follows a practical approach and gives you access to all relevant code files hosted at github.com/PacktPublishing/Flutter-for-Beginners. This will help you access a variety of examples and prepare your own bug-free apps, ready to deploy on the App Store and Google Play Store.
By the end of this book, you’ll be well-versed with Dart programming and have the skills to develop your own mobile apps or build a career as a Dart and Flutter app developer.
What you will learn- Understand the fundamentals of the Dart programming language
- Explore the core concepts of the Flutter UI and how it compiles for multiple platforms
- Develop Flutter plugins and widgets and understand how to structure plugin code appropriately
- Style your Android and iOS apps with widgets and learn the difference between stateful and stateless widgets
- Add animation to your UI using Flutter's AnimatedBuilder component
- Integrate your native code into your Flutter codebase for native app performance
This book is for developers looking to learn Google's revolutionary framework Flutter from scratch. No prior knowledge of Flutter or Dart is required; however, basic knowledge of any programming language will be helpful.
Read more from Alessandro Biessek
Flutter for Beginners: Cross-platform mobile development from Hello, World! to app release with Flutter 3.10+ and Dart 3.x Rating: 0 out of 5 stars0 ratingsFlutter for Beginners: An introductory guide to building cross-platform mobile applications with Flutter and Dart 2 Rating: 0 out of 5 stars0 ratingsFlutter for Beginners: An introductory guide to building cross-platform mobile applications with Flutter 2.5 and Dart Rating: 0 out of 5 stars0 ratings
Related to Flutter for Beginners
Related ebooks
Flutter and Dart: Up and Running: Build native apps for both iOS and Android using a single codebase (English Edition) Rating: 0 out of 5 stars0 ratingsApplication Development with Swift Rating: 0 out of 5 stars0 ratingsGetting Started with React Native Rating: 4 out of 5 stars4/5Learning Bootstrap Rating: 1 out of 5 stars1/5Flutter For Dummies Rating: 0 out of 5 stars0 ratingsBeginning Flutter: A Hands On Guide to App Development Rating: 0 out of 5 stars0 ratingsFlutter in Action Rating: 1 out of 5 stars1/5Learning Dart - Second Edition Rating: 0 out of 5 stars0 ratingsDart Cookbook Rating: 0 out of 5 stars0 ratingsDart By Example Rating: 0 out of 5 stars0 ratingsDart Essentials Rating: 0 out of 5 stars0 ratingsMastering React Native Rating: 5 out of 5 stars5/5Dart in Action Rating: 0 out of 5 stars0 ratingsAndroid application development with Kotlin: Build Your First Android App In No Time Rating: 0 out of 5 stars0 ratingsMastering Dart Rating: 0 out of 5 stars0 ratingsMastering Android Application Development Rating: 5 out of 5 stars5/5Designing Microservices using Django: Structuring, Deploying and Managing the Microservices Architecture with Django Rating: 0 out of 5 stars0 ratingsReact Projects: Build 12 real-world applications from scratch using React, React Native, and React 360 Rating: 0 out of 5 stars0 ratingsUltimate Flutter for Cross-Platform App Development Rating: 0 out of 5 stars0 ratingsReactJS by Example - Building Modern Web Applications with React Rating: 4 out of 5 stars4/5Kivy – Interactive Applications and Games in Python - Second Edition Rating: 0 out of 5 stars0 ratingsReact: Building Modern Web Applications Rating: 5 out of 5 stars5/5React Native By Example Rating: 0 out of 5 stars0 ratingsReact.js Essentials Rating: 4 out of 5 stars4/5Ultimate Flutter Handbook: Learn Cross-Platform App Development with Visually Stunning UIs and Real-World Projects Rating: 0 out of 5 stars0 ratingsNext.js Cookbook: Learn how to build scalable and high-performance apps from scratch (English Edition) Rating: 0 out of 5 stars0 ratingsLearning AngularJS Animations Rating: 4 out of 5 stars4/5Django Design Patterns and Best Practices Rating: 5 out of 5 stars5/5
Programming For You
Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsJavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5iPhone For Dummies Rating: 0 out of 5 stars0 ratingsSQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Code like a Pro in C# Rating: 0 out of 5 stars0 ratingsLinux: Learn in 24 Hours Rating: 5 out of 5 stars5/5HTML & CSS: Learn the Fundaments in 7 Days Rating: 4 out of 5 stars4/5Python: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5HTML in 30 Pages Rating: 5 out of 5 stars5/5C Programming for Beginners: Your Guide to Easily Learn C Programming In 7 Days Rating: 4 out of 5 stars4/5PYTHON: Practical Python Programming For Beginners & Experts With Hands-on Project Rating: 5 out of 5 stars5/5Python Data Structures and Algorithms Rating: 5 out of 5 stars5/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5C All-in-One Desk Reference For Dummies Rating: 5 out of 5 stars5/5Learn PowerShell in a Month of Lunches, Fourth Edition: Covers Windows, Linux, and macOS Rating: 5 out of 5 stars5/5
Reviews for Flutter for Beginners
0 ratings0 reviews
Book preview
Flutter for Beginners - Alessandro Biessek
Flutter for Beginners
An introductory guide to building cross-platform mobile applications with Flutter and Dart 2
Alessandro Biessek
BIRMINGHAM - MUMBAI
Flutter for Beginners
Copyright © 2019 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.
Commissioning Editor: Amarabha Banerjee
Acquisition Editor: Larissa Pinto
Content Development Editor: Akhil Nair
Technical Editor: Sachin Sunilkumar
Copy Editor: Safis Editing
Project Coordinator: Manthan Patel
Proofreader: Safis Editing
Indexer: Pratik Shirodkar
Production Designer: Jyoti Chauhan
First published: September 2019
Production reference: 2260220
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-78899-608-2
www.packt.com
To my mother, Antonina, and my father, Euclides, for their sacrifices and for exemplifying the power of determination
– Alessandro Biessek
mapt.io
Subscribe to our online digital library for full access to over 7,000 books and videos, as well
as industry leading tools to help you plan your personal development and advance your
career. For more information, please visit our website.
Why subscribe?
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Fully searchable for easy access to vital information
Copy and paste, print, and bookmark content
Packt.com
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Contributors
About the author
Alessandro Biessek was born in the beautiful city of Chapecó, in the state of Santa Catarina, southern Brazil, in 1993. He is currently working on mobile application development for Android and iOS in his hometown. He has more than 7 years of experience in development, from desktop development with Delphi to backend with PHP, Node.js, Golang, mobile development with Apache Flex, and Java/Kotlin. Most of his time is devoted to the development of Android apps. Always interested in new technologies, he has been following the Flutter framework for a long time, shown through its growth and adoption in recent months.
Firstly, thanks to the Flutter team for their incredible tool that is helping the developer community to help other people.
I am grateful to all of those with whom I have had the pleasure to work with during this project, all the reviewers, and the entire Packt team who helped me in this work.
I’d like to thank my friends, coworkers and family, especially my mother Antonina, my father Euclides, my sister Hellen and my brother Alan, for being supportive and for holding the fort while I worked hard on the book. Also, thanks to my graduation teachers, who encouraged me to face challenges like this book in a more natural and brave way.
Finally, I'd like to thank you, the reader. Your support of books such as this, through your purchase, makes it possible for everyone who wants to share their experiences to continue.
About the reviewer
Ugurcan Yildirim is an enthusiast of Android and Flutter mobile application development frameworks. He graduated as valedictorian with a BSc degree in Computer Science from Bilkent University, Ankara. Since 2015, he has been working as an Android Engineer at Accenture Industry X.0, Istanbul. With Flutter's promising uptrend that started in 2018, he began to concern himself with the peculiarities of Flutter and experiment with them. Since then, he has contributed to the open source community of Flutter by writing articles on Medium (@ugurcany) and giving presentations. His latest contribution is to review this book, which he believes should be consulted and referenced by Flutter developers of any level.
I would like to thank Packt for giving me the opportunity to contribute to the ever-expanding Flutter universe by reviewing one of the first and most comprehensive Flutter books published. I would also like to thank my parents and my wife, Karsu, for their support and patience over the course of reviewing this book.
Packt is searching for authors like you
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Table of Contents
Title Page
Copyright and Credits
Flutter for Beginners
Dedication
About Packt
Why subscribe?
Packt.com
Contributors
About the author
About the reviewer
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Conventions used
Get in touch
Reviews
Section 1: Introduction to Dart
An Introduction to Dart
Getting started with Dart
The evolution of Dart
How Dart works
Dart VM and JavaScript compilation
Hands-on Dart
DartPad
Dart development tools
Hello world
Understanding why Flutter uses Dart
Adding productivity
Compiling Flutter apps and hot reload
Easy learning
Maturity
Introducing the structure of the Dart language
Dart operators
Arithmetic operators
Increment and decrement operators
Equality and relational operators
Type checking and casting
Logical operators
Bits manipulation
Null-safe and null-aware operators
Dart types and variables
final and const
Built-in types
Numbers
BigInt
Booleans
Collections
Strings
String interpolation
Literals
Type inference – bringing dynamism to the show
Control flows and looping
Functions
Function parameters
Data structures, collections, and generics
Generics
When and why to use generics
Generics and Dart literals
Introduction to OOP in Dart
Dart OOP features
Objects and classes
Encapsulation
Inheritance and composition
Abstraction
Polymorphism
Summary
Further reading
Intermediate Dart Programming
Dart classes and constructors
The enum type
The cascade notation
Constructors
Named constructors
Factory constructors
Field accessors – getters and setters
Static fields and methods
Class inheritance
The toString() method
Interfaces, abstract classes, and mixins
Abstract classes
Interfaces
Mixins – adding behavior to a class
Callable classes, top-level functions, and variables
Callable classes
Top-level functions and variables
Understanding Dart libraries and packages
Importing and using a library
Importing show and hide
Importing prefixes to libraries
Importing path variants
Creating Dart libraries
Library member privacy
The library definition
A single-file library
Splitting libraries into multiple files
A multiple-file library – the export statement
Dart packages
Application packages versus library packages
Package structures
Stagehand – the Dart project generator
The pubspec file
Package dependencies – pub
Specifying dependencies
The version constraint
The source constraint
Introducing async programming with Futures and Isolates
Dart Futures
Dart Isolates
Introducing unit testing with Dart
The Dart test package
Writing unit tests
Summary
An Introduction to Flutter
Comparisons with other mobile app development frameworks
The problems Flutter wants to solve
Differences between existing frameworks
High performance
Full control of the UI
Dart
Being backed by Google
Fuchsia OS and Flutter
Open source framework
Developer resources and tooling
Flutter compilation (Dart)
Development compilation
Release compilation
Supported platforms
Flutter rendering
Web-based technologies
Framework and OEM widgets
Flutter – rendering by itself
Widgets introduction
Composability
Immutability
Everything is a widget
The widget tree
Hello Flutter
pubspec file
Running the generated project
lib/main.dart file
Flutter run
Summary
Section 2: The Flutter User Interface - Everything is a Widget
Widgets: Building Layouts in Flutter
Stateful versus stateless widgets
Stateless widgets
Stateful widgets
Stateful and stateless widgets in code
Stateless widget in code
Stateful widgets in code
Inherited widgets
Widget key property
Built-in widgets
Basic widgets
The Text widget
The Image widget
Material Design and iOS Cupertino widgets
Buttons
Scaffold
Dialogs
Text fields
Selection widgets
Date and time pickers
Other components
Understanding built-in layout widgets
Containers
Styling and positioning
Other widgets (gestures, animations, and transformations)
Creating a UI with widgets (favor manager app)
The app screens
The app code
Favors app home screen
The layout code
The request favor screen
The layout code
Creating custom widgets
Summary
Handling User Input and Gestures
Handling user gestures
Pointers
Gestures
Tap
Double tap
Press and hold
Drag, pan, and scale
Horizontal drag
Vertical drag
Pan
Scale
Gestures in material widgets
Input widgets
FormField and TextField
Using a controller
Accessing FormField state
Form
Accessing Form state
Using a key
Using InheritedWidget
Validating Input (Forms)
Validating user input
Custom input and FormField
Creating custom inputs
Custom input widget example
Creating an Input widget
Turn the widget into a FormField widget
Putting it all together
Favors screen
Tap gestures on the favor tab
Tap gestures on FavorCards
Making FavorsPage a StatefulWidget
Refuse action handling
Do action handling
Tap on Request a favor button
The Requesting a favor screen
The close button
The SAVE button
Validating input using the Form widget
Summary
Theming and Styling
Theme widgets
Theme widget
ThemeData
Brightness
Theming in practice
Platform class
Material Design
MaterialApp widget
Scaffold widget
Custom theme
iOS Cupertino
CupertinoApp
Cupertino in practice
Using custom fonts
Importing fonts to the Flutter project
Overriding the default font in the app
Dynamic styling with MediaQuery and LayoutBuilder
LayoutBuilder
MediaQuery
MediaQuery example
Additional responsive classes
Summary
Routing: Navigating between Screens
Understanding the Navigator widget
Navigator
Overlay
Navigation stack/history
Route
RouteSettings
MaterialPageRoute and CupertinoPageRoute
Putting it all together
The WidgetsApp way
Named routes
Moving to named routes
Arguments
Retrieving results from Route
Screen transitions
PageRouteBuilder
Custom transitions in practice
Hero animations
The Hero widget
Implementing Hero transitions
Summary
Section 3: Developing Fully Featured Apps
Firebase Plugins
Firebase overview
Setting up Firebase
Connecting the Flutter app to Firebase
Configuring an Android app
Configuring iOS app
FlutterFire
Adding the FlutterFire dependency to the Flutter project
Firebase authentication
Enabling Authentication services in Firebase
Authentication screen
Logging in with Firebase
Sending verification code
Verifying the SMS code
Updating the profile and login status
NoSQL database with Cloud Firestore
Enabling Cloud Firestore on Firebase
Cloud Firestore and Flutter
Loading favors from Firestore
Updating favors on Firebase
Saving a favor on Firebase
Cloud Storage with Firebase Storage
Introduction to Firebase Storage
Adding Flutter Storage dependencies
Uploading files to Firebase
Ads with Firebase AdMob
AdMob account
Creating an AdMob account
AdMob in Flutter
Side note on Android
Side note on iOS
Showing ads in Flutter
ML with Firebase ML Kit
Adding ML Kit to Flutter
Using the label detector in Flutter
Summary
Developing Your Own Flutter Plugin
Creating a package/plugin project
Flutter packages versus Dart packages
Starting a Dart package project
Starting a Flutter plugin package
A plugin project structure
MethodChannel
Implementing the Android plugin
Implementing the iOS plugin
The Dart API
An example of plugin package
Using the plugin
Adding documentation to the package
Documentation files
Library documentation
Generating documentation
Publishing a package
Plugin project development recommendations
Summary
Accessing Device Features from the Flutter App
Launching a URL from the app
Displaying a link
The flutter_linkify plugin
Launching a URL
The url_launcher plugin
Managing app permissions
Managing permissions on Flutter
Using the permission_handler plugin
Importing a contact from the phone
Importing a contact with contact_picker
Contact permission with permission_handler
Contact permission on Android
Contact permission on iOS
Checking and requesting permission in Flutter (permission_handler)
Integrating the phone's camera
Taking pictures with image_picker
Camera permission with permission_handler
Camera permission on Android
Camera permission on iOS
Requesting camera permission in Flutter (permission_handler)
Summary
Platform Views and Map Integration
Displaying a map
Platform views
Enabling platform views on iOS
Creating a platform view widget
Creating an Android view
Creating an iOS view
Usage of a platform view widget
Getting started with the google_maps_flutter plugin
Displaying a map with the google_maps_flutter plugin
Enabling the Maps API on Google Cloud Console
Google Maps API integration on Android
Google Maps API integration on iOS
Displaying a map on Flutter
Adding markers to the map
The Marker class
Adding markers in the GoogleMap widget
Adding map interactions
Adding markers dynamically
GoogleMapController
Getting GoogleMapController
Animating a map camera to a location
Using the Google Places API
Enabling the Google Places API
Getting started with the google_maps_webservice plugin
Getting a place address using the google_maps_webservice plugin
Summary
Section 4: Advanced Flutter - Resources to Complex Apps
Testing, Debugging, and Deployment
Flutter testing – unit and widget testing
Widget tests
The flutter_test package
The testWidgets function
Widget test example
Debugging Flutter apps
Observatory
Additional debugging features
DevTools
Profiling Flutter apps
The Observatory profiler
Profile mode
Performance overlay
Inspecting the Flutter widget tree
Widget inspector
The Flutter inspector in DevTools
Preparing apps for deployment
Release mode
Releasing apps for Android
AndroidManifest and build.gradle
AndroidManifest – permissions
AndroidManifest – meta tags
AndroidManifest – application name and icon
build.gradle – application ID and versions
build.gradle – signing the app
Releasing apps for iOS
App Store Connect
Xcode
Xcode – application details and Bundle ID
Xcode – AdMob
Xcode – signing the app
Summary
Improving User Experience
Accessibility in Flutter and adding translations to apps
Flutter's support for accessibility
Flutter internationalization
The intl package
The intl_translation package
The flutter_localizations package
Adding localizations to a Flutter app
Dependencies
The AppLocalization class
Generating .arb files with intl_translation
Using translated resources
Communication between native and Flutter with platform channels
Platform channel
Message codecs
Creating background processes
The Flutter compute() function
SendPort and ReceivePort
IsolateNameServer
A compute() example
Full background process
Init the calculation
The background isolate
Adding Android-specific code to run Dart code in the background
The HandsOnBackgroundProcessPlugin class
The BackgroundProcessService class
The PluginRegistrantCallback property
Adding iOS-specific code to run Dart code in the background
The SwiftHandsOnBackgroundProcessPlugin class
Summary
Widget Graphic Manipulations
Transforming widgets with the Transform class
The Transform widget
Understanding the Matrix4 class
Exploring the types of transformations
Rotate transformation
Scale transformation
Translate transformation
Composed transformations
Applying transformations to your widgets
Rotating widgets
Scaling widgets
Translating widgets
Applying multiple transformations
Using custom painters and canvas
The Canvas class
Canvas transformations
Canvas ClipRect
Methods
The Paint object
The CustomPaint widget
CustomPaint construction details
The CustomPainter object
The paint method
The shouldRepaint method
A practical example
Defining a widget
Defining CustomPainter
Overriding the shouldRepaint method
Overriding the paint method
The radial chart variant
Defining a widget
Defining CustomPainter
Summary
Animations
Introducing Animations
The Animation<T> class
AnimationController
TickerProvider and Ticker
CurvedAnimation
Tween
Using animations
Rotate animation
Scale animation
Translate animation
Multiple transformations and custom Tween
Custom Tween
Using AnimatedBuilder
The AnimatedBuilder class
Revisiting our animation
Using AnimatedWidget
The AnimatedWidget class
Rewriting the animation with AnimatedWidget
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
Preface
Flutter for Beginners helps you to enter the Flutter framework world and build awesome mobile applications. I'll take you from an introduction to the Dart language to an in-depth exploration of all the Flutter blocks needed to make a high-level app. Together, we will build a fully featured app. With clear code examples, you will learn how to start a small Flutter project, add some widgets, apply styles and themes, connect with remote services such as Firebase, get user input, add some animations to improve the user experience, and more. In addition, you will learn how to add advanced features, map integrations, work with platform-specific code with native programming languages, and create fantastic UIs with personalized animations. In short, this book will prepare you for the future of mobile development with this amazing framework.
Who this book is for
This book is for developers looking to learn Google's revolutionary framework, Flutter, from scratch. No knowledge of Flutter or Dart is required. However, basic programming language knowledge will be helpful.
What this book covers
Chapter 1, An Introduction to Dart, introduces the basics of the Dart language.
Chapter 2, Intermediate Dart Programming, looks at object-oriented programming features and advanced concepts from Dart, libraries, packages and asynchronous programming.
Chapter 3, An Introduction to Flutter, introduces you to the world of Flutter.
Chapter 4, Widgets: Building Layouts in Flutter, looks at how to build layouts in Flutter.
Chapter 5, Handling User Input and Gestures, shows you how to handle user input with Flutter widgets.
Chapter 6, Theming and Styling, teaches you how to apply different styles to Flutter widgets.
Chapter 7, Routing: Navigating between Screens, explores how to add navigation to app screens.
Chapter 8, Firebase Plugins, covers how to use Firebase plugins in Flutter apps.
Chapter 9, Developing Your Own Flutter Plugin, explains how to create your own Flutter plugins.
Chapter 10, Accessing Device Features from the Flutter App, dives into how to interact with device features such as cameras and contact lists.
Chapter 11, Platform Views and Map Integration, shows you how to add map views to Flutter applications.
Chapter 12, Testing, Debugging, and Deployment, delves into Flutter tools for improving productivity.
Chapter 13, Improving User Experience, explores how to improve user experience using features such as background Dart execution and internationalization.
Chapter 14, Widget Graphic Manipulations, gets into how to create unique visuals with graphic manipulations.
Chapter 15, Animations, gives you an insight into how to add animations to Flutter widgets.
To get the most out of this book
You will be introduced to the requirements as we move through the chapters. To get started, you need to have access to a browser so you can access the DartPad website and play with Dart code.
To professionally develop and publish iOS apps, you need a developer license (paid annually), a Mac, and at least one device to test the applications. All this is not strictly necessary for the purpose of learning Flutter, but it might be useful to you.
The entire installation process and the requirements of the Flutter environment are available on the official website (https://flutter.dev/docs/get-started/install), but do not worry: you can start with the bare minimum and install any extras only when necessary.
Download the example code files
You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at www.packt.com.
Select the Support tab.
Click on Code Downloads.
Enter the name of the book in the Search box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Flutter-for-Beginners. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Download the color images
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781788996082_ColorImages.pdf.
Conventions used
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. Here is an example: It evaluates and returns the value of expression2: expression1 ?? expression2.
A block of code is set as follows:
main() {
var yeahDartIsGreat = Obviously!
;
var dartIsGreat = yeahDartIsGreat ?? I don't know
;
print(dartIsGreat); // prints Obviously!
}
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
main() {
var someInt = 1;
print(reflect(someInt).type.reflectedType.toString()); // prints: int
}
Any command-line input or output is written as follows:
dart code.dart
Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: Also, the floating action button at the bottom end should redirect you to the Request a favor screen.
Warnings or important notes appear like this.
Tips and tricks appear like this.
Get in touch
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and 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 would report this to us. Please visit www.packtpub.com/support/errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
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 authors.packtpub.com.
Reviews
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packt.com.
Section 1: Introduction to Dart
In this section, you will gain an understanding of the core Flutter framework, explore the basics of the Dart language, learn how to set up your own environment, and finally, learn how to get started with it.
The following chapters are included in this section:
Chapter 1, An Introduction to Dart
Chapter 2, Intermediate Dart Programming
Chapter 3,An Introduction to Flutter
An Introduction to Dart
The Dart language is present at the core of the Flutter framework. A modern framework such as Flutter requires a high-level modern language to be capable of providing the best experience to the developer and making it possible to create awesome mobile applications. Understanding Dart is fundamental to working with Flutter; developers need to know the origins of the Dart language, how the community is working on it, its strengths, and why it is the chosen programming language to develop with Flutter. In this chapter, you will review the basics of the Dart language and be provided with some links to resources that can help you on your Flutter journey. You will review Dart built-in types and operators, and how Dart works with object-oriented programming (OOP). By understanding what the Dart language provides, you will be able to comfortably experiment with the Dart environment by yourself and expand your knowledge.
We will be covering the following topics in this chapter:
Getting to know the principles and tools of the Dart language
Understanding why Flutter uses Dart
Learning the basics of the Dart language structure
Introducing OOP with Dart
Getting started with Dart
The Dart language, developed by Google, is a programming language that can be used to develop web, desktop, server-side, and mobile applications. Dart is the programming language used to code Flutter apps, enabling it to provide the best experience to the developer for the creation of high-level mobile applications. So, let's explore what Dart provides and how it works so we can later apply what we learn in Flutter.
Dart aims to aggregate the benefits of most of the high-level languages with mature language features, including the following:
Productive tooling: This includes tools to analyze code, integrated development environment (IDE) plugins, and big package ecosystems.
Garbage collection: This manages or deals with memory deallocation (mainly memory occupied by objects that are no longer in use).
Type annotations (optional): This is for those who want security and consistency to control all of the data in an application.
Statically typed: Although type annotations are optional, Dart is type-safe and uses type inference to analyze types in runtime. This feature is important for finding bugs during compile time.
Portability: This is not only for the web (transpiled to JavaScript), but it can be natively compiled to ARM and x86 code.
The evolution of Dart
Unveiled in 2011, Dart has been evolving ever since. Dart saw its stable release in 2013, with major changes included in the release of Dart 2.0 toward the end of 2018:
It was focused on web development in its conception, with the main aim of replacing JavaScript:However, now Dart is focused on mobile development areas as well as on Flutter.
It tried solving JavaScript's problems: JavaScript doesn't provide the robustness that many consolidated languages do. So, Dart was launched as a mature successor to JavaScript.
It offers the best performance and better tools for large-scale projects: Dart has modern and stable tooling provided by IDE plugins. It's been designed to get the best possible performance while keeping the feel of a dynamic language.
It is molded to be robust and flexible: By keeping the type annotations optional and adding OOPfeatures, Dart balances the two worlds of flexibility and robustness.
Dart is a great modern cross-platform, general-purpose language that continually improves its features, making it more mature and flexible. That's why the Flutter framework team chose the Dart language to work with.
How Dart works
To understand where the language's flexibility came from, we need to know how we can run Dart code. This is done in two ways:
Dart Virtual Machines (VMs)
JavaScript compilations
Have a look at the following diagram:
Dart VM and JavaScript compilation
Dart code can be run in a Dart-capable environment. A Dart-capable environment provides essential features to an app, such as the following:
Runtime systems
Dart core libraries
Garbage collectors
The execution of Dart code operates in two modes—Just-In-Time (JIT) compilation or Ahead-Of-Time (AOT) compilation:
A JIT compilation is where the source code is loaded and compiled to native machine code by the Dart VM on the fly. It is used to run code in the command-line interface or when you are developing a mobile application in order to use features such as debugging and hot reloading.
An AOT compilation is where the Dart VM and your code are precompiled and the VM works more like a Dart runtime system, providing a garbage collector and various native methods from the Dart software development kit (SDK) to the application.
Dart contributes to Flutter's most famous feature, hot reload, which is based on the Dart JIT compiler, allowing fast interactions with live code swaps. See the Understanding why Flutter uses Dart section for details.
Hands-on Dart
The way Flutter is designed is heavily influenced by the Dart language. So, knowing this language is crucial for success in the framework. Let's start by writing some code to understand the basics of the syntax and the available tools for Dart development.
DartPad
The easiest way to start coding is to use the DartPad tool (https://dartpad.dartlang.org/). It is a great online tool to learn and experiment with Dart's language features. It supports Dart's core libraries, except for VM libraries such as dart:io.
This is what the tool looks like:
Dart development tools
DartPad is the perfect way to start experimenting with the language without any extra effort. Since you will soon want to learn advanced things such as writing on files or using custom libraries, you'll need to have a development environment configured for that.
Flutter is based on Dart and you can develop Dart code by having a Flutter development environment. To find out how to configure a Flutter development environment, just refer to the official website for the installation tutorial (https://dart.dev/tools/sdk#install).
The most common IDEs used for Dart and Flutter development are Visual Studio Code or VS Code (for the web and Flutter), and Android Studio or any JetBrains IDE such as WebStorm (which is web-focused). All of the Dart functionalities of these IDEs are based on official tools, so it doesn't matter what you choose—the provided tools will be mostly the same. The Dart SDK provides specialized tools for each development ecosystem, such as web and server-side programming.
The standalone Dart SDK ships with the following tools:
dart (https://dart.dev/tools/dart-vm): This is the standalone Dart VM; this executes Dart code. To execute a Dart script, run the following command:
dart code.dart
dart2js (https://dart.dev/tools/dart2js): This is the original Dart-to-JavaScript compiler.
dartanalyzer (https://github.com/dart-lang/sdk/tree/master/pkg/analyzer_cli#dartanalyzer): This statically analyzes code (as a typical linter), helping to catch errors early.
Lint, or a linter, is a tool that analyzes source code to flag errors, bugs, stylistic errors, and suspicious constructs.
dartdoc (https://github.com/dart-lang/dartdoc#dartdoc): This generates the API reference documentation.
pub (https://dart.dev/tools/pub/cmd): This is a package manager. It is a tool that can be used for the management of libraries and packages.
dartfmt (https://github.com/dart-lang/dart_style#readme): This applies style guidelines to Dart code.
For web development, Dart adds some tools (with additional installation steps at https://dart.dev/tools):
webdev (https://dart.dev/tools/webdev) and build_runner (https://dart.dev/tools/webdev): Both of these tools are used for building and serving web apps, with build_runner being used in testing or when more configuration is required than webdev provides.
dartdevc (https://dart.dev/tools/dartdevc): This is powered for dev Dart-to-JavaScript compiler-like integration with Chrome tools.
dart2js is also a web-focused tool, although it ships with