Support Statistics
¥.00 ·
0times
Text Preview (First 20 pages)
Registered users can read the full content for free
Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.
Page
1
Rose Flutter & D a rt C ookb ook Flutter & D a rt C ookb ook
Page
2
Richard Rose Foreword by Majid Hajian Flutter and Dart Cookbook Developing Full-Stack Applications for the Cloud
Page
3
978-1-098-11951-5 [LSI] Flutter and Dart Cookbook by Richard Rose Copyright © 2023 Richard Rose. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (https://oreilly.com). For more information, contact our corporate/institu‐ tional sales department: 800-998-9938 or corporate@oreilly.com. Acquisitions Editor: Suzanne McQuade Development Editor: Jeff Bleiel Production Editor: Jonathon Owen Copyeditor: nSight Inc. Proofreader: Arthur Johnson Indexer: Potomac Indexing LLC Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Kate Dullea December 2022: First Edition Revision History for the First Edition 2022-12-14 First Release 2023-01-19 Second Release See https://www.oreilly.com/catalog/errata.csp?isbn=0636920635109 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Flutter and Dart Cookbook, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. The views expressed in this work are those of the author and do not represent the publisher’s views. While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights.
Page
4
Table of Contents Foreword. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix 1. Learning Dart Variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.1 Running a Dart Application 2 1.2 Working with Integer Values 3 1.3 Working with Double Values 4 1.4 Working with Boolean Values 4 1.5 Working with Strings 5 1.6 Printing Information to the Console 6 1.7 Adding a Constant Variable (Compile Time) 7 1.8 Adding a Constant Variable (Runtime) 8 1.9 Working with Null Variables 8 2. Exploring Control Flow. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 2.1 Verifying That a Condition Has Been Met 11 2.2 Iterating Until a Condition Is Met 13 2.3 Iterating over a Range of Items 15 2.4 Performing Conditional Actions Based on a Value 16 2.5 Using an Enumerator to Represent Values 18 2.6 Implementing Exception Handling 19 3. Implementing Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 3.1 Declaring Functions 21 3.2 Adding Parameters to Functions 22 3.3 Using Optional Parameters 23 3.4 Returning Values from Functions 25 iii
Page
5
3.5 Declaring Anonymous Functions 26 3.6 Adding a Functional Delay Using a Future 27 4. Handling Lists and Maps. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 4.1 Creating Lists of Data 29 4.2 Amending a List of Data 31 4.3 Using Lists with Complex Types 32 4.4 Handling Map Key/Value Pairings 33 4.5 Printing Map Data Structure Content 35 4.6 Validating That Content Exists in a Map 36 4.7 Printing Complex Data Types 36 5. Getting Started with Object-Oriented Dart. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 5.1 Beginning Object-Oriented Dart 40 5.2 Creating a Class 41 5.3 Initializing a Class Using a Constructor 42 5.4 Adding Class Inheritance 44 5.5 Adding a Class Interface 46 5.6 Adding a Class Mixin 49 6. Dart Test Cases. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 6.1 Adding the Dart Test Package to Your Application 54 6.2 Creating a Sample Test Application 55 6.3 Running Unit Tests in Your Dart Application 56 6.4 Grouping Multiple Unit Tests 58 6.5 Adding Mock Data for Testing 61 7. Introducing the Flutter Framework. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 7.1 Mocking an Application Interface 66 7.2 Creating a Boilerplate Flutter Project 67 7.3 Removing the Flutter Debug Banner 69 7.4 Recognizing Widgets 70 7.5 Understanding the Widget Tree 71 7.6 Improving Widget Render Performance 72 8. Adding Assets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 8.1 Using the pubspec.yaml File 75 8.2 Adding an Assets Folder 77 8.3 Referencing an Image 78 8.4 Incorporating the Google Fonts Package 80 8.5 Importing a Package 81 iv | Table of Contents
Page
6
9. Working with Widgets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 9.1 Creating a Stateless Widget in Flutter 83 9.2 Creating a Stateful Widget in Flutter 85 9.3 Refactoring Flutter Widgets 88 9.4 Using the Scaffold Class 91 9.5 Adding an AppBar Header 94 9.6 Building with a Container 96 9.7 Using a Center Widget 99 9.8 Using a SizedBox 101 9.9 Using a Column 104 9.10 Using a Row 108 9.11 Using an Expanded Widget 110 10. Developing User Interfaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 10.1 Using the Google Fonts Package 115 10.2 Incorporating RichText 117 10.3 Identifying the Host Platform 119 10.4 Using a Placeholder Widget 121 10.5 Using a LayoutBuilder 123 10.6 Accessing Screen Dimensions Using MediaQuery 126 11. Organizing On-Screen Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 11.1 Implementing a Vertical ListView 132 11.2 Implementing a Horizontal ListView 135 11.3 Adding a SliverAppBar 138 11.4 Adding a SliverList 140 11.5 Adding a GridView of Items 144 11.6 Adding a SnackBar (Pop-Up Notification) 147 12. Flutter Page Navigation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 12.1 Adding Page Navigation with Routes (Imperative) 151 12.2 Adding Page Navigation with Routes (Declarative) 155 12.3 Implementing a Navigation Drawer 159 12.4 Working with Tabs 164 12.5 Adding a Bottom Navigation Bar 167 12.6 Using Keys to Pass Information 170 13. Handling Data Assets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 13.1 Accessing Data Strategically 174 13.2 Refactoring Data 176 13.3 Generating Dart Classes from JSON 178 13.4 Using Local JSON Data Asynchronously 180 Table of Contents | v
Page
7
13.5 Consuming a JSON Dataset from the Assets Folder 185 13.6 Accessing Remote JSON Data 188 14. Testing the Flutter User Interface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191 14.1 Automated Widget Testing in Flutter 191 14.2 Performing Automated Widget Testing 194 14.3 Performing Integration Testing with Flutter Driver 195 14.4 Testing Android/iOS Device Compatibility 196 15. Working with Firebase and Flutter. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199 15.1 Using the Firebase Platform with Flutter 200 15.2 Setting Up a Firebase Project 201 15.3 Initializing the Firebase SDK for Local Development 203 15.4 Configuring Firebase Emulators 205 15.5 Adding flutterfire_cli to a Development Environment 208 15.6 Integrating a Firestore Database 210 15.7 Writing Data to a Firestore Database 213 15.8 Reading Data from Cloud Firestore 217 15.9 Adding Firebase Authentication to Flutter 222 15.10 Using Flutter Web with Firebase Hosting 228 16. Introducing Cloud Services. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231 16.1 Getting Started with Cloud Providers 232 16.2 Working with Identity and Access Management 232 16.3 Using Cloud Storage to Host an Object 234 16.4 Developing a Backend HTTP Server with Dart 235 16.5 Building a Dart Container 237 16.6 Introducing Serverless with Dart 238 17. Starting with Game Development. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241 17.1 Adding the Flame Package to Flutter 242 17.2 Creating a Flame Boilerplate 243 17.3 Adding a Sprite 244 17.4 Adding Manual Horizontal Movement to a Sprite 246 17.5 Adding Automated Vertical Movement to a Sprite 249 17.6 Adding Collision Detection 252 17.7 Adding Text Rendering 255 17.8 Adding Graphic Primitives 259 17.9 Adding Sound Effects 265 Appendix: Setting Up Your Environment. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281 vi | Table of Contents
Page
8
Foreword Every day I see people building amazing apps and creating great content with Flutter and Dart. Both Flutter and Dart help developers learn faster and pursue their dreams. When Rich Rose told me he was writing this book, I knew it would help thousands of developers. This cookbook’s practical, example-driven approach provides a fascinating way to learn Flutter and Dart. As an early adopter of Flutter and Dart, Rich has done a tre‐ mendous job of sharing numerous valuable tips and tricks. It’s a great desk reference in which you’ll find answers to many questions that you face in your daily work. I’m happy to recommend this book, and I hope it helps you unlock the potential of the fantastic experience of building Flutter apps and working with the Dart language. —Majid Hajian Google Developer Expert for Flutter and Dart and Head of Developer Relations at Invertase Oslo, November 2022 vii
Page
9
(This page has no text content)
Page
10
Preface Welcome to the Flutter and Dart Cookbook. If you haven’t heard of Flutter, it’s the multiplatform framework that is taking the development community by storm. Dart provides a rich software development kit (SDK) underpinning Flutter. Rather than having to learn multiple technologies, Flutter enables you to target Android, iOS, Linux, the web, and Windows from a single code base. As someone who watches a lot of YouTube, I am always deeply impressed with the example applications created. Flutter and Dart have been instrumental in not only making me love coding again but also allowing me to meet some awesome Flutter community folks. The Flutter community is pretty dope and continues to deliver high-quality content— shout-out to YouTubers and Google Developer communities dedicating time and effort to help people get a foothold in the software industry. Whether you are a seasoned developer or are just getting started, Flutter makes devel‐ opment fun. It’s very quick to learn and super powerful, allowing integration with powerful cloud-based solutions such as Firebase. Get started today and build an application for the next million users. Who Should Read This Book Whether or not you know Flutter and Dart, you have heard that irresistible call to go out and build something. Ignore the desire to procrastinate, and get started building the future. So how do you maintain motivation and get to the point you are able to deliver an application? Read this book. The beauty of learning Flutter and Dart is it has a very low barrier to entry. Developing an application requires both skill and effort. There is a reason software engineers are paid a lot of money. Whether you have experience in multiple lan‐ guages or have zero experience developing software, Flutter and Dart is a great ix
Page
11
starting point to creating stunning applications. From the first day, you can quickly become productive and produce beautiful applications with very little effort. Building applications involves lots of moving pieces as well as integrating with exter‐ nal services. Learn the fundamentals of working with the Firebase suite and take your first steps with Cloud. Get started building games and then follow along to under‐ stand the building blocks for the Flame game engine. Why I Wrote This Book I was first introduced to Flutter when my wife started learning the language using a Flutter development course created by Google. The main thing that stood out to me was the speed at which applications were built and how nice they looked. The imme‐ diate productivity boost was impressive, and I was quickly hooked on building simple multiplatform apps. When I was starting out learning this new technology, there were a number of things which were either not obvious or just difficult to remember. I would have loved to have this cookbook to sit beside me while working on that course. Now there are even more superb courses available online, but the lingering question still remains, How do you do x in Flutter? For some readers, this book will complement your existing knowledge as you undertake your journey to create applications. For others, it will represent that safety blanket that you can use to guide and support your journey as a Flutter developer. Navigating This Book Getting started with any language can present lots of uncertainty as you wonder where to start and what you need to know. While I really want you to read the book from cover to cover, realistically you will likely jump directly to the Flutter chapters. With that in mind, the book features broad categories to give you the opportunity to dip into the subject matter as required. The general categories are as follows: • Chapters 1 and 2 provide a high-level introduction to the Dart language to help you work with the basics such as variables and control flow. • Chapters 3 to 6 give you a rapid immersion into the essential elements of the Dart language that will help you use the language productively. • Chapters 7 to 14 cover the Flutter language and demonstrate the basics of render‐ ing widgets on-screen. If I had to guess, this is the section you will reference the most when developing applications that require widget creation and data management. • Chapters 15 and 16 cover working in the cloud and specifically Firebase to add authentication, databases, and hosting. x | Preface
Page
12
• Chapter 17 deals with using the Flame game engine and gives you the essentials of this package. If you have a weekend free, you can use this to recreate the game Frogger. • The Appendix covers the stuff that you need to know to set up your environment such as installing the Flutter framework, using Flutter Doctor, and working in an IDE. Conventions Used in This Book The following typographical conventions are used in this book: Italic Indicates new terms, URLs, email addresses, filenames, and file extensions. Constant width Used for program listings, as well as within paragraphs to refer to program ele‐ ments such as variable or function names, databases, data types, environment variables, statements, and keywords. Constant width bold Shows commands or other text that should be typed literally by the user. Constant width italic Shows text that should be replaced with user-supplied values or by values deter‐ mined by context. This element signifies a general note. This element signifies a general note. O’Reilly Online Learning For more than 40 years, O’Reilly Media has provided technol‐ ogy and business training, knowledge, and insight to help companies succeed. Preface | xi
Page
13
Our unique network of experts and innovators share their knowledge and expertise through books, articles, and our online learning platform. O’Reilly’s online learning platform gives you on-demand access to live training courses, in-depth learning paths, interactive coding environments, and a vast collection of text and video from O’Reilly and 200+ other publishers. For more information, visit https://oreilly.com. How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at https://oreil.ly/fl-dt-ckbk. Email bookquestions@oreilly.com to comment or ask technical questions about this book. For news and information about our books and courses, visit https://oreilly.com. Find us on LinkedIn: https://linkedin.com/company/oreilly-media Follow us on Twitter: https://twitter.com/oreillymedia Watch us on YouTube: https://www.youtube.com/oreillymedia Acknowledgments This edition is dedicated to my lovely wife, who inspired me to learn Flutter, only so she could get me to fix her applications. :-) Thanks to my family, who, despite Dad being busy writing this book, always made time to play music noisily or come and have an impromptu chat when I was deep in concentration. Seriously, though, thanks to Dawn, Bailey, Elliot, Noah, and Amelia. Over the course of a year, working on this book has become more than a project—it has become an inspiration. Special thanks to Dylan Peck, Casey Palowitch, Alessandro Palmieri, and Andrew Brogdon for the support and the opportunity to deliver Flutter to the Google Devel‐ oper Group community. It’s acts like this that make the difference, and, from personal experience, know that these sessions are really appreciated. xii | Preface
Page
14
I also want to thank the technical reviewers—Alex Moore, Rob Edwards, and Majid Hajian—for some great insight and feedback. While it’s not easy writing a book, it is super helpful to have access to folks who are willing to dedicate their spare time and help deliver something like this. Really appreciate the effort and the time spent by each of you. My deepest thanks to Jeff Bleiel for being a fantastic editor and someone who made this process very enjoyable and significantly less stressful than it should have been. Thanks also to Zan McQuade and Jonathon Owen at O’Reilly. Preface | xiii
Page
15
(This page has no text content)
Page
16
CHAPTER 1 Learning Dart Variables In this chapter, we focus on learning the basics of using variables in Dart. As you might expect, Dart offers a rich set of variable data types. To quickly get up to speed in the language, it is vitally important to know the basic data types. If you are familiar with the use of variables in other programming languages, under‐ standing variables in Dart should not be too difficult to grasp. Use this chapter as a quick guide to cement your understanding before moving on to more complex topics. For beginners, this chapter will introduce you to the fundamentals. Ultimately it should offer a quick technical guide as you progress in your journey to learn Dart/ Flutter. Across the chapter, the code examples are self-contained and are focused on a typical use case. We start by discussing the four main variable types (i.e., int, double, bool, and String) and how each is used. Finally, we learn how to let Dart know what we want to do with our variables (i.e., final, const, and null). We also cover the subject of immutability, which refers to the ability to change the value associated with a variable. An immutable variable is one that cannot be changed. In Dart, the keywords const and final make a variable immutable . A key nuance of immutability is whether the variable is checked at compile time or runtime. Compile time refers to checks applied at the code building stage (i.e., const vari‐ ables). Runtime refers to checks performed at the application execution stage (i.e., final variables). As of Dart 2.0, the language is type-safe, meaning that once a variable is declared, the type cannot be changed. For example, if a variable of type double is declared, it can‐ not then be used as an int without explicit casting. Before we dive into how to use variables, we need to ensure the programming environment is correctly set up. 1
Page
17
1.1 Running a Dart Application Problem You want to run a dart application. Solution Dart code can be run within your environment once the SDK has been installed. To learn how to install the SDK, see the Appendix. Open a terminal session to allow the entry of commands. If you are using an IDE, the terminal needs to be opened within that application. Now confirm that Dart is installed on the device by checking the version as shown here: dart --version If the command responds successfully, you should see the version of the SDK installed and the platform you are running on. If the command is unsuccessful, you will need to check the installation and path for your device. Now, in your editor, create a new file named main.dart and add the following contents: void main() { print('Hello, Dart World!'); } Run your example code from the command line as follows: dart main.dart This command should output “Hello, Dart World!” Discussion The dart command is available as part of the Dart SDK installation. In the preceding example, the command will run a file named main.dart. Dart applications have the extension .dart and can be run either from the command line or within an IDE (e.g., Android Studio or VS Code). Note: neither Android Studio nor VS Code are precon‐ figured to include Dart/Flutter functionality. You will need to install the relevant plug-in (in addition to installing the SDK) before being able to run any code. If you don’t want to install Dart within your environment, use the online editor avail‐ able at DartPad. If you are unable to run the dart command, it’s likely that the SDK has not been installed correctly. Use the latest installation instructions to confirm the installation on your device. 2 | Chapter 1: Learning Dart Variables
Page
18
1.2 Working with Integer Values Problem You want to store a number without a decimal point. Solution Use an integer variable to store a number without a decimal point. If you want to store an integer value of 35, the declaration would be as follows: void main() { int myVariable = 35; print(myVariable); } In the Dart language, an integer uses the reference int. In the preceding code exam‐ ple, the data type (e.g., int) is the first part of the declaration. Next, a label is assigned to the data type to be used, e.g., myVariable. Finally, we assign a value to the data type—in this example, the value of 35. To use the data type, a variable is declared, e.g., myVariable. A variable is a label used to reference the data type created. Once a variable is available, you can assign a value to the data type. In the example, the integer 35 is assigned to the variable myVariable. A print statement is then used to output the variable value. Discussion Dart follows a set pattern for declaration of variables. The prefix declares the data type to be used; this is followed by a variable label and then an optional assignment. In this example, the data type to be used is an int. An integer is represented by num‐ bers that do not have a decimal point. The typical use case for an int is a number that doesn’t require a decimal point (i.e., precision). An integer is defined as a 64-bit inte‐ ger number. The integer data type is a subtype of num, which includes basic opera‐ tions, e.g., +/–, etc. The variable label provides a means to reference the int data type in the example code. Our example uses the label myVariable. When naming a variable, try to make the name relevant to the purpose of the variable. To complete the variable declaration, a value is assigned. Here we assign the value of 35 to our variable, meaning when we reference this, we expect the value of 35 to be used for our int data type. 1.2 Working with Integer Values | 3
Page
19
If the integer variable were not initialized, it would mean a value could not be accessed. In this situation, Dart will return an error indicating the value we are trying to access is a non-nullable variable. Essentially, this means we have not assigned a value to a variable we are attempting to access. In most instances, this is an error, and the Dart compiler will helpfully tell us we have made a mistake. If you do in fact wish to use a nullable variable, you would need to tell Dart how to handle this situation. Learn more about handling null values in Recipe 1.9. 1.3 Working with Double Values Problem You want to store a number with a decimal point. Solution Use a double (precision) variable to store a number including a decimal point. If you want to store a double value of 2.99, declare the following: void main() { double myVariable = 2.99; print(myVariable); } Similar to other variables, prefix the variable with the desired data type, e.g., double. The variable will then require a label to be assigned, e.g., myVariable. Finally, assign a value to the data type—in this example, the value of 2.99. Discussion In the previous example, we begin by indicating the data type to be used, i.e., double. Following that, we provide a variable name (in our example, myVariable) for double. The last part, where a value is assigned to the variable, is optional. The typical use case for a double data type is a number requiring a level of precision. A double data type is a 64-bit floating-point number. Double is a subtype of num, which includes basic operations, e.g., +/–, etc. 1.4 Working with Boolean Values Problem You want to store a true/false value. 4 | Chapter 1: Learning Dart Variables
Page
20
Solution Use a bool variable to store a true/false state. Declare a Boolean variable using the keyword bool, following the data type declara‐ tion with a label for the variable name, e.g., myVariable. Finally, assign a value to the variable of either true or false. Here’s an example of how to declare a bool: void main() { bool myVariable = true; print(myVariable); } Discussion In the preceding example, we begin by indicating the data type to be used, i.e., bool. Following that, we provide a variable name for the defined data type. The last part is optional, where we assign a value to the named variable. The use case for a bool is that of a true/false scenario. Note that true and false are reserved keywords in Dart. Reserved in this context indicates the word has a defined meaning in terms of the language. A boolean data type includes logic operations, e.g., and, equality, inclusive or, exclusive or. 1.5 Working with Strings Problem You want to store a sequence of characters. Solution Use a String variable to store a series of text. Here’s an example of how to declare a String: void main() { String myVariable = "I am a string"; String myVariable2 = """ I am a multiline string """; print(myVariable); } 1.5 Working with Strings | 5
Comments 0
Loading comments...
Reply to Comment
Edit Comment