Main Pragmatic Flutter: Building Cross-Platform Mobile Apps for Android, iOS, Web & Desktop

Pragmatic Flutter: Building Cross-Platform Mobile Apps for Android, iOS, Web & Desktop

,
0 / 0
How much do you like this book?
What’s the quality of the file?
Download the book for quality assessment
What’s the quality of the downloaded files?
Have you ever thought of creating beautiful blazing fast native apps for iOS and Android from a single codebase? Have you dreamt of taking your native apps to the web and desktop without costing a fortune? If so, this book, Pragmatic Flutter: Building Cross-Platform Mobile Apps for Android, iOS, Web & Desktop, is the right place to start your journey to developing cross-platform apps. Google's Flutter is the brand-new way for developing beautiful, fluid, and blazing fast cross-platform apps for Android, iOS, web, and desktops (macOS, Linux, Windows). Google's new Fuchsia OS UI is implemented using Flutter as well. Learning to develop mobile apps with Flutter opens the door to multiple devices, form-factors, platforms using a single codebase. You don't need any prior experience using Dart to follow along this book. However, its recommended to have some familiarity writing code using one of the object-oriented programming languages. You will start your journey with learning to structure and organize the Flutter project to develop apps for multiple platforms. Next, you will explore fundamentals of Flutter widgets. You will continue your journey of widgets with Flutter's layout widgets while learning to build responsive layouts. You will get an understanding of organizing and applying themes and styles, handling user input, and gestures. Then you will move on to advanced concepts like fetching data over the network, integrating and consuming REST API in your app. You will get hands-on experience on design patterns, data modeling, routing, navigation for multi-screen apps. When you are finished with this book, you will have a solid foundational knowledge of Flutter that will help you move forward in your journey building great and successful mobile apps that can be deployed to Android, iOS, web, and desktop (macOS) platforms from a single code base.
Year:
2021
Edition:
1
Publisher:
CRC Press
Language:
english
Pages:
272
ISBN 10:
0367612097
ISBN 13:
9780367612092
File:
PDF, 9.86 MB
Download (pdf, 9.86 MB)
Conversion to is in progress
Conversion to is failed

Most frequently terms

 
0 comments
 

To post a review, please sign in or sign up
You can write a book review and share your experiences. Other readers will always be interested in your opinion of the books you've read. Whether you've loved the book or not, if you give your honest and detailed thoughts then people will find new books that are right for them.
1

Cloud Without Compromise: Hybrid Cloud for the Enterprise

Year:
2021
Language:
english
File:
EPUB, 8.98 MB
0 / 0
2

Computer Organization and Design

Year:
2021
Language:
english
File:
EPUB, 606 KB
0 / 0
Pragmatic Flutter

Pragmatic Flutter
Building Cross-Platform Mobile Apps
for Android, iOS, Web, & Desktop

Priyanka Tyagi

First edition published 2022
by CRC Press
6000 Broken Sound Parkway NW, Suite 300, Boca Raton, FL 33487-2742
and by CRC Press
2 Park Square, Milton Park, Abingdon, Oxon, OX14 4RN
© 2022 Taylor & Francis Group, LLC
CRC Press is an imprint of Taylor & Francis Group, LLC
The right of Priyanka Tyagi to be identified as author of this work has been asserted by her in accordance
with sections 77 and 78 of the Copyright, Designs and Patents Act 1988.
Reasonable efforts have been made to publish reliable data and information, but the author and publisher cannot assume responsibility for the validity of all materials or the consequences of their use.
The authors and publishers have attempted to trace the copyright holders of all material reproduced in
this publication and apologize to copyright holders if permission to publish in this form has not been
obtained. If any copyright material has not been acknowledged please write and let us know so we may
rectify in any future reprint.
Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced,
transmitted, or utilized in any form by any electronic, mechanical, or other means, now known or hereafter invented, including photocopying, microfilming, and recording, or in any information storage or
retrieval system, without written permission from the publishers.
For permission to photocopy or use material electronically from this work, access www.copyright.com
or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA 01923, 978750-8400. For works that are not available on CCC please contact mpkbookspermissions@tandf.co.uk
Trademark notice: Product or corporate names may be trademarks or registered trademarks and are used
only for identification and explanation without intent to infringe.
ISBN: 978-0-367-61209-2 (hbk)
ISBN: 978-1-032-05565-7 (pbk)
ISBN: 978-1-003-10463-6 (e; bk)
Typeset in Times LT Std
by KnowledgeWorks Global Ltd.

To my husband Krishna
And my children Kalp and Krisha
Who inspired me to start writing this book and finish it!

Contents
Preface.................................................................................................................... xiii
Author....................................................................................................................... xv
Chapter 1

Dart Fundamentals: A Quick Reference to Dart 2................................1
The main Function...............................................................................1
Variables & Data Types.........................................................................2
Collections.............................................................................................2
Spread Operator....................................................................................3
Transform List Items.............................................................................3
Filtering.................................................................................................3
Adding Item...........................................................................................4
Removing Item......................................................................................4
Adding Multiple Items..........................................................................4
Intersection of Two Set(s)......................................................................5
Union of Two Set(s)...............................................................................5
Checking for Key..................................................................................6
Checking for Value................................................................................7
Accessing all Values..............................................................................7
Iterating Key/Value Pairs......................................................................7
Functions...............................................................................................8
Classes................................................................................................. 10
Conclusion........................................................................................... 12
References........................................................................................... 12

Chapter 2

Introduction to Flutter......................................................................... 15
Cross-Platform Solutions..................................................................... 15
Why Flutter......................................................................................... 18
Conclusion...........................................................................................20
References...........................................................................................20

Chapter 3

Setting Up Environment...................................................................... 23
System Requirements for macOS........................................................ 23
Setting Up Flutter SDK....................................................................... 23
Setting Up for the Android Platform...................................................25
Setting Up for the iOS Platform.......................................................... 27
Setting Up for Web..............................................................................28
Setting Up for Desktop........................................................................ 29
Source Code Online............................................................................ 31

vii

viii

Contents

Setting Up Editor................................................................................. 32
Conclusion........................................................................................... 32
References........................................................................................... 32
Chapter 4

Flutter Project Structure...................................................................... 35
Choosing Flutter Channel................................................................... 35
Creating Flutter Project....................................................................... 36
Cross-Platform Flutter Project Structure............................................ 39
Running Default App: Android, iOS, Web, and Desktop...................40
Running Code Samples....................................................................... 41
Useful Commands............................................................................... 45
Conclusion...........................................................................................46
References...........................................................................................46

Chapter 5

Flutter App Structure.......................................................................... 47
Flutter Widgets.................................................................................... 48
Display ‘Hello Books’ Text................................................................. 49
Add Cushion Around the Text............................................................ 51
Center the Text.................................................................................... 53
App Anatomy #1................................................................................. 53
App Anatomy #2................................................................................. 53
Conclusion........................................................................................... 61
References........................................................................................... 61

Chapter 6

Flutter Widgets.................................................................................... 63
Image Widget.................................................................................... 63
ToggleButtons Widget.................................................................. 65
TextField Widget........................................................................... 68
FutureBuilder Async Widget...................................................... 71
Placeholder Widget....................................................................... 74
StreamBuilder Async Widget...................................................... 76
AlertDialog Widget...................................................................... 78
Conclusion........................................................................................... 83
References...........................................................................................84

Chapter 7

Building Layouts................................................................................. 87
Revisiting HelloBooksApp Layout...................................................... 87
Types of Layout Widgets..................................................................... 89
Container Widget...........................................................................90
Padding Widget................................................................................97
ConstrainedBox Widget...............................................................99
SizedBox Widget........................................................................... 101
Row Widget....................................................................................... 103

Contents

ix

IntrinsicHeight Widget............................................................ 105
Column Widget................................................................................ 110
IntrinsicWidth Widget.............................................................. 112
ListView Widget............................................................................ 115
GridView Widget............................................................................ 117
Table Widget................................................................................... 117
Stack Widget................................................................................... 119
IndexedStack Widget.................................................................. 121
Conclusion......................................................................................... 123
References......................................................................................... 124
Chapter 8

Responsive Interfaces........................................................................ 127
FittedBox Widget......................................................................... 127
Expanded Widget........................................................................... 128
Flexible Widget............................................................................ 132
FractionallySizedBox Widget................................................ 134
LayoutBuilder Widget................................................................ 137
Wrap Widget..................................................................................... 137
Conclusion......................................................................................... 139
References......................................................................................... 141

Chapter 9

Building User Interface for BooksApp............................................. 143
The BooksApp Interface.................................................................... 143
The BooksApp Anatomy................................................................... 143
Implementing User Interface............................................................. 144
Custom Widget: BooksListing.................................................... 148
Conclusion......................................................................................... 151
References......................................................................................... 151

Chapter 10 Flutter Themes.................................................................................. 153
Global Theme.................................................................................... 153
Modularizing Themes....................................................................... 157
Using Custom Fonts.......................................................................... 159
Local Theme..................................................................................... 160
Switching Themes............................................................................. 163
Conclusion......................................................................................... 167
References......................................................................................... 168
Chapter 11 Persisting Data................................................................................... 169
Light Theme (Default)....................................................................... 169
Key/Value Data Store (Shared Preferences Plugin).......................... 169

x

Contents

Local Database (Moor Library)........................................................ 173
Light Theme on Multiple Platforms.................................................. 180
Dark Theme on Multiple Platforms.................................................. 182
Conclusion......................................................................................... 186
References......................................................................................... 187
Chapter 12 Integrating REST API....................................................................... 189
What Is an API?................................................................................ 189
Flutter Configuration......................................................................... 190
API Key............................................................................................. 190
API Endpoint..................................................................................... 192
Building Simple Interface................................................................. 193
Running Code................................................................................... 196
Adding Entitlement........................................................................... 198
AndroidManifest.xml........................................................................ 199
Conclusion.........................................................................................200
References......................................................................................... 201
Chapter 13 Data Modeling...................................................................................203
Parsing JSON.................................................................................... 203
ListView Widget: Listing Entries..................................................207
Custom Widget: BookTile.............................................................209
Constructing Data Model.................................................................. 217
Converting API Response to BookModel List............................... 220
Run the Code..................................................................................... 221
Conclusion......................................................................................... 227
References......................................................................................... 228
Chapter 14 Navigation and Routing..................................................................... 229
Simple BookDetailsPage Screen................................................ 229
Navigator Widget............................................................................... 232
Direct Navigation.............................................................................. 233
Detecting Gesture.............................................................................. 233
Passing Data...................................................................................... 234
Static Navigation............................................................................... 235
Detecting Gesture.............................................................................. 236
Passing Data...................................................................................... 236
Dynamic Navigation......................................................................... 237
The generateRoute() Function.................................................. 237
Detecting Gesture.............................................................................. 238
Passing Data...................................................................................... 238
Conclusion......................................................................................... 239
References......................................................................................... 239

Contents

xi

Chapter 15 The Second Page – BookDetailsPage Widget................................... 241
Anatomy of BookDetailsPage Widget....................................... 241
BookDetailsPage Screen’s Layout............................................. 242
Implementing BookDetailsPage Widget.................................... 243
Conclusion......................................................................................... 249
References......................................................................................... 249
Chapter 16 Introduction to State Management.................................................... 251
Revisiting Default CounterApp......................................................... 251
Vanilla Pattern................................................................................... 252
Conclusion......................................................................................... 255
References......................................................................................... 256
Chapter 17 ValueNotifier..................................................................................... 257
Using ValueNotifier Approach.......................................................... 257
Conclusion......................................................................................... 262
References......................................................................................... 262
Chapter 18 Provider and ChangeNotifier............................................................. 265
What Is Provider.......................................................................... 265
What Is ChangeNotifier............................................................266
Anatomy of CounterApp...................................................................266
Increasing Counter............................................................................ 267
Custom Widget: CountWidget...................................................... 267
Finished Implementation................................................................... 268
Conclusion......................................................................................... 270
References......................................................................................... 270
Chapter 19 BLoC Design Pattern........................................................................ 271
What Is BLoC Pattern?..................................................................... 271
Anatomy of CounterApp................................................................... 271
Basic BLoC Pattern Implementation................................................. 273
Event StreamController............................................................ 276
Event Sink....................................................................................... 276
Event Stream/CounterBloc Constructor................................... 276
State StreamController............................................................. 277
State Sink........................................................................................ 277
State Stream.................................................................................... 277
Improvised BLoC Pattern Implementation....................................... 279
State StreamController.............................................................280
State Sink........................................................................................280

xii

Contents

State Stream.................................................................................... 281
Implementing BLoC Pattern Using Library...................................... 282
Conclusion......................................................................................... 285
References......................................................................................... 285
Chapter 20 Unit Testing....................................................................................... 287
Package Dependencies...................................................................... 287
The CounterApp................................................................................ 287
Test File............................................................................................. 292
Running Unit Tests............................................................................ 294
Conclusion......................................................................................... 295
References......................................................................................... 295
Chapter 21 Widget Testing................................................................................... 297
Package Dependency......................................................................... 297
Testing Widgets................................................................................. 298
Running Widget Tests....................................................................... 305
Conclusion......................................................................................... 305
References......................................................................................... 305
Chapter 22 Integration Testing.............................................................................307
Package Dependency.........................................................................307
Preview CounterApp Code................................................................307
Test Pair Files.................................................................................... 310
Writing Integration Tests................................................................... 310
Running Integration Tests................................................................. 313
Conclusion......................................................................................... 314
References......................................................................................... 314
Chapter 23 Rolling into the World....................................................................... 315
Adding Launcher Icon....................................................................... 315
Releasing Android Apps................................................................... 316
Releasing iOS Apps........................................................................... 322
Releasing Web Apps.......................................................................... 327
Releasing Desktop (macOS) Apps.................................................... 330
Conclusion......................................................................................... 331
References......................................................................................... 331
Index....................................................................................................................... 333

Preface
Have you ever thought of creating beautiful blazing-fast native apps for iOS and
Android from a single codebase? Have you dreamt of taking your native apps to the
web and desktop without costing a fortune? If so, this book is the right place to start
your journey of developing cross-platform apps.
Google’s Flutter software development kit (SDK) is the latest way of developing
beautiful, fluid cross-platform apps for Android, iOS, Web, and Desktops (macOS,
Linux, Windows). Google’s new Fuchsia OS user interface (UI) is implemented
using Flutter as well. Learning to develop mobile apps with Flutter opens the door to
multiple devices, form-factors, and platforms from a single codebase.
You don’t need any prior experience using Dart to follow along with this book.
However, it’s recommended to have some familiarity with writing code in one of
the object-oriented programming languages like Java and Python. You will pick up
the fundamentals of Dart 2 language in the first chapter. We will learn to structure
and organize the multi-platform Flutter project and test the setup by running the
same code on Android, iOS, web, and desktop platforms. Next, we will explore basic
Flutter widgets along with layout widgets while building a non-trivial UI. Later on,
we will continue learning to build responsive layouts for different screen sizes and
form-factors.
We will be organizing and applying themes and styles, handling user input, and
gestures. Then we will move on to fetching data over the network, integrating, and
consuming REST API in app. We will build a BooksApp to display books listing
from Google Books API and integrate this API to fetch book data. Different types of
testing strategies will be introduced to develop solid and high-quality apps. You will
get hands-on experience using state management solutions, data modeling, routing,
and navigation for multi-screen apps. You will learn to use Flutter plugins to persist
data in the app. This book concludes by giving the pointers to deploy and distribute
your Flutter app across all four platforms.
When you finish this book, you will have a solid foundational knowledge of
Flutter SDK that will help you move forward in your journey of building great and
successful mobile apps that can be deployed to Android, iOS, web, and desktop
(macOS) from a single code base.
Throughout the book, italic is used to render file, folder, and Flutter application
names. The monospace font is used to represent code snippets, variable names, and
data structures. All examples used in this book are available online in the GitHub
repository: https://github.com/ptyagicodecamp/pragmatic_flutter.
Last but definitely not least, I want to acknowledge the input of my fellow developers Rajalakshmi Balaji, Preetika Tyagi, and Snehal Patil without whom this book
wouldn’t be possible. I am also thankful to the Flutter community worldwide for sharing their expertise and knowledge for developing great cross-platform applications.

xiii

Author
Priyanka Tyagi is a Software Engineering Manager at Willow Innovations, Inc.,
which builds products that improve the lives and health of women. At Willow
Innovations, Inc., she is helping to build a better wearables experience by using
Flutter and Bluetooth Low Energy (BLE) technologies.
Priyanka has many years of experience designing and developing software,
web, and mobile systems for a diverse range of industries from automobile and
e-­commerce to entertainment and EdTech to health and wellness. Her expertise lies
in Flutter, Android, Firebase, Mobile SDKs, AWS/Google cloud-based solutions,
cross-platform apps, and game-based learning. In her previous roles, she has worked
with Disney Interactive as Lead Android Engineer. She has also helped various startups with her software engineering consulting services.
Priyanka loves to share her tech explorations around mobile apps development
and other software engineering topics in her tech blog: https://priyankatyagi.dev/.
She is an Internet of Things (IOT) enthusiast and volunteers her time at local
public schools to introduce computer science to young minds. She volunteers for
the Hour of Code initiative to inspire young developers in the tech world for many
years. Priyanka is passionate about mentoring aspiring developers to get started in
the tech industry. She earned an MS in computer science from Illinois Institute of
Technology, Chicago.
Priyanka lives with her husband and two kids in beautiful California. She loves to
read, bake, and hike in her free time.

xv

1 A Quick Reference to Dart 2
Dart Fundamentals

Dart programming language is developed by Google. It has been around since 2011.
However, it has gained popularity recently since Google announced Flutter software
development kit (SDK) for developing cross-platform-applications. Dart aims to help
developers build web and mobile applications effectively. It works for building
production-ready solutions for client applications as well as for the server-side. Dart
has an Ahead-of-Time (AOT) compiler that compiles predictable native code quickly
for the target platform. It is optimized to build customized user interfaces natively
for multiple platforms. The Dart is a developers-friendly programming language. It
is easy for developers coming from different programming language backgrounds to
learn Dart without much effort.
The Dart 2 (Announcing Dart 2 Stable and the Dart Web Platform) is the latest version of Dart language including the rewrite of many features, improved performance and
productivity. This chapter covers the basics of Dart 2 language syntaxes (Google, 2020)
to get started with the journey of building applications using Flutter. A prior understanding of object-oriented programming is needed to follow along with the material. Dart 2
and Dart will be used to infer the Dart 2 programming language in this book. In the
upcoming topics, we’ll review some of the language features with the help of examples.

THE main FUNCTION
The `main()` function is the entry point for any Dart program. The following code
snippet will print “Hello Dart” on the console. Open a ‘Terminal’ at MacOS or its
Windows or Linux equivalent. Create a file say ‘hello.dart’, and copy the following
code snippet in it.
```
void main() {
print("Hello Dart");
}
```

Running Dart Program
Go back to the ‘Terminal’ and execute the file using `dart hello.dart`. The
“Hello Dart” is printed on the console.
```
$ dart hello.dart
Hello Dart
```
1

2

Pragmatic Flutter

VARIABLES & DATA TYPES
In Dart, you can use the `var` keyword to infer the underlying data type. The following code snippet shows declaring variable `data` to hold the numeric value ‘1’.
```
var data = 1;
print(data);
```

The above code snippet will print the ‘1’ on the console. The runtimeType (runtimeType property) property gives the runtime type of the object it’s called on. The following code snippet will print the data type of the `data` variable as ‘int’ on the console.
```
var data = 1;
print(data.runtimeType);
```

It’s valid for the `data` variable to get reassigned to a value from a different data type.
There’s another keyword, `dynamic`, to assign a value to a variable similar to
the `var` keyword. The difference between the two is that for the `dynamic` keyword, the same variable can be reassigned to a different data type, as shown in the
code snippet below:
```
// Assigning int to dynamicData
dynamic dynamicData = 1;
// Prints `int` as data type on console
print(dynamicData.runtimeType);
//Re-assigning dynamicData to String data type
dynamicData = "I'm a string now";
// Prints `String` as data type on console
print(dynamicData.runtimeType);
```

Source Code Online
The source code for this example (Chapter01: Quick Reference to Dart2 (Variables
& Data Types)) is available at GitHub.

COLLECTIONS
List
Dart’s List (List<E> class) is a collection that holds indexable objects. An empty
list can is declared using two square brackets ‘[]’. List items can be put inside these
brackets separated by commas.
```
List emptyList = [];

Dart Fundamentals

3

//Checking if List is empty
var result = emptyList.isEmpty;
print(result);
```

SPREAD OPERATOR
Dart 2.3 introduced the spread operator (Spread Operator) and null aware spread
operator to combine multiple lists into one. Let’s create a list `theList` with two
items and a null list `theNullList`. If you want to merge these two lists into
another list, say `anotherList`, it can be done using spread (...) and null aware
spread (?...) operators.
```
List theList = ['Dart', 'Kotlin'];
//null list
List theNullList;
// Spread operator ... - Flatten the list and to be merged
with another list
// Null spread operator ...? - Helps to avoid runtime
exceptions - iterator called on null.
List anotherList = ['Java', ...theList, ...?theNullList];
// Printing the merged list created using spread operators
print(anotherList);
// Output
[Java, Dart, Kotlin]
```

TRANSFORM LIST ITEMS
The `map` on the `List` can be called to transform the list items. Let’s append the
word ‘Language’ to objects of the `theList` list.
```
List theList = ['Dart', 'Kotlin'];
result = theList.map((e) => "$e Language").toList();
print(result);
// Output
[Dart Language, Kotlin Language]
```

FILTERING
The `where` method on `List` can help filter items meeting specific criteria. In the
following code snippet, we are filtering the words containing the letter ‘a’. Since only
‘Dart’ matches these criteria, `result` will hold only the word ‘Dart’.

4

Pragmatic Flutter

```
List theList = ['Dart', 'Kotlin'];
result = theList.where((element) =>
element.toString().contains('a'));
print(result); // Dart contains letter 'a'
// Output
(Dart)
```

Set
The Set (Set<E> class) data structure holds a collection of objects only once. The duplicates are not allowed when storing data in `Set`. Let’s create two sets to learn the usage.
```
Set langSet = {'Dart', 'Kotlin', 'Swift'};
Set sdkSet = {'Flutter', 'Android', 'iOS'};
```

ADDING ITEM
Let’s add a new item ‘Java’ in the `langSet` and print the final set.
```
// Adding 'Java' to Set
langSet.add('Java');
print(langSet);
// Output
{Dart, Kotlin, Swift, Java}
```

REMOVING ITEM
Let’s remove the newly added item ‘Java’ from `langSet` and print the final set.
```
// Remove Java from Set
langSet.remove('Java');
print(langSet);
// Output
{Dart, Kotlin, Swift}
```

ADDING MULTIPLE ITEMS
More than one item can be added all at once in `Set` using the `addAll()` method.
It accepts the list of items. Let’s add multiple items to both sets.

Dart Fundamentals

5

```
// Adding multiple items to each set
langSet.addAll(['C#', 'Java']);
sdkSet.addAll(['C#', 'Xamarin']);
print(langSet);
print(sdkSet);
// Output
{Dart, Kotlin, Swift, C#, Java}
{Flutter, Android, iOS, C#, Xamarin}
```

INTERSECTION OF TWO SET(S)
The `intersection` method on `Set` returns the shared items from both sets.
The `langSet` and `sdkSet` both contain the ‘C#’ item in them. The intersection
on those sets will return the ‘C#’.
```
// Find Intersection of two sets (common items)
result = langSet.intersection(sdkSet);
print(result); // C#
// Output
{C#}
```

UNION OF TWO SET(S)
The `union` returns items combined from `langSet` and `sdkSet` without any
duplicates. Both sets contain ‘C#’, and it’ll be added in the `result` only once.
```
// Find a Union of two sets. No duplicates.
result = langSet.union(sdkSet);
print(result);
// Output
{Dart, Kotlin, Swift, C#, Java, Flutter, Android, iOS, Xamarin}
```

Map
The Map (Map<K, V> class) data structure is a collection that contains key/value
pairs. A value is accessed using the key for that entry. Let’s create a `Map` with a key
of `int` type, and value is of `String` type.
One way to create a Map `intToStringMap` is as below:
```
var intToStringMap = Map<int, String>();
```

6

Pragmatic Flutter

The new key/value pair can be added as shown in the code snippet below:
```
intToStringMap[1] = '1';
intToStringMap[2] = '2';
```

The first or last entry of the map can be accessed using `first` and `last` properties of entries (entries property) iterable.
```
// first Map entry
result = intToStringMap.entries.first;
print(result);
// Output
MapEntry(1: 1)
// last Map entry
result = intToStringMap.entries.last;
print(result);
// Output
MapEntry(2: 2)
```

Let’s create a `Map` with the key and value of type `String` as below:
```
var techMap = {
'Flutter': 'Dart',
'Android': 'Kotlin',
'iOS': 'Swift',
};
```

CHECKING FOR KEY
The `containsKey(String key)` method on the map returns a boolean true or
false depending on whether the given `key` exists in the Map or not.
```
// Returns boolean. true if key is found, otherwise false
result = techMap.containsKey('Flutter');
print(result);
// Output
true
```

Dart Fundamentals

7

CHECKING FOR VALUE
The `containsValue(String value)` method returns the boolean value as
‘true’ if the given value exists in the Map.
```
// Checking if value is present in the Map
result = techMap.containsValue('Dart');
print(result);
// Output
true
```

ACCESSING ALL VALUES
All values of the key/value pairs in Map collection can be accessed calling
`foreach` on `values` as below:
```
// Prints all values
techMap.values.forEach((element) {
print("$element");
});
// Output
Dart
Kotlin
Swift
```

ITERATING KEY/VALUE PAIRS
All key/value pairs in Map collection are iterated, as shown in the code below:
```
// Iterates over all key-value pairs and prints them
techMap.entries.forEach((element) {
print("${element.value} is used for developing

${element.key} applications.");
});
// Output
Dart is used for developing Flutter applications.
Kotlin is used for creating Android applications.
Swift is used for developing iOS applications.
```

Source Code Online
The source code for this example (Chapter01: Quick Reference to Dart2 (Collections))
is available at GitHub.

8

Pragmatic Flutter

FUNCTIONS
Let’s create a function that checks if the passed argument is ‘Flutter’ or not and
returns a boolean value. It returns true if it’s precise ‘Flutter’ or false otherwise. Such functions are known as ‘Named Function’ because the function’s name
describes what they are intended to.
```
bool isFlutter(String str) {
return str == 'Flutter';
}
// Using Named Function
dynamic result = isFlutter("Flutter");
print(result);
//Output
true
```

Function with Optional Parameters
Let’s create a function `concat(...)` that joins two strings together when the second string is available. In such a case, the second string can be passed as optional
using square brackets ‘[]’.
```
String concat(String str1, [String str2]) {
return str2 != null ? "$str1 $str2" : str1;
}
// Usage
result = concat("Priyanka", "Tyagi");
print(result);
//Output
Priyanka Tyagi
```

Named Parameters
The other way to provide optional parameters is to use named parameters. They can
be passed using curly braces ‘{}’.
```
// Named Parameters: Function with optional parameters in
curly braces
String concat2(String str1, {String str2}) {
return str2 != null ? "$str1 $str2" : str1;
}

Dart Fundamentals

9

// Using function with optional params with curly braces{}
result = concat2("Priyanka", str2: "Tyagi");
print(result);
// Output
Priyanka Tyagi
```

Passing Function as Parameter
The Dart 2 programming language allows passing a function as a parameter to
another function. Let’s create a function `int subtract(int a, int b)`
to find the difference between the two values ‘a’ and ‘b’. The method `calculate(...)` takes two numbers and a function as a parameter to operate on the
values passed.
```
int subtract(int a, int b) {
return a > b ? a - b : b - a;
}
// Passing Function as parameter
int calculate(int value1, int value2, Function(int, int)
function) {
return function(value1, value2);
}
//Passing function 'subtract' as parameter
result = calculate(5, 4, subtract);
print(result);
// Output
1
```

Arrow Syntax
The arrow syntax can be used to write functions in one line. Let’s write the function
to add two numbers using arrow syntax as below:
```
// Arrow Syntax
int add(int a, int b) => a + b;
// Using Arrow Syntax
result = add(5, 4);
print(result);
//Output
9
```

10

Pragmatic Flutter

Anonymous Function
Anonymous functions don’t have a name and can be assigned to a variable either
using the keyword `var` or `Function`.
```
// Anonymous Function
Function anonymousAdd = (int a, int b) {
return a + b;
};
// Using anonymous functions.
// Calling function variable `anonymousAdd`
result = anonymousAdd(4, 5);
print(result);
//Output
9
```

Source Code Online
The source code for this example (Chapter01: Quick Reference to Dart2 (Functions))
is available at GitHub.

CLASSES
Dart classes are created using the keyword `class`. Let’s define a class Person to
represent a person in the real world. This person has a name, an age, and the food it eats.
```
class Person {
String name;
int age;
String food;
}
```

Constructor
Dart supports easy to use constructors. Let’s see two types of constructors. The
short-form constructor looks like below. The first part is required. The parameters
inside ‘[]’ are optional.
```
Person(this.name, [this.age]);
//Usage
Person person = Person("Priyanka");
```

Dart Fundamentals

11

Another type of constructor is the named constructor. All parameters are enclosed
in the curly braces ‘{}’.
```
Person.basicInfo({this.name, this.age});
//Usage
Person child = Person.basicInfo(name: "Krisha", age: 6);
```

Getters
The getters in Dart classes are defined using the `get` keyword. Let’s create a getter
`personName` to get the name.
```
String get personName => this.name;
```

Setters
The setters in the Dart classes are defined using the `set` keyword. Let’s create a
setter `personName` to set the name as below:
```
set personName(String value) => this.name = value;
```

Method
Let’s add a method to the class `Person` to define the eating behavior. The method
`eats(String food)` takes the food as `String` and assigns it to the class `food`
property.
```
void eats(String food) {
this.food = food;
}
// Usage
Person child = Person.basicInfo(name: "Krisha", age: 6);
child.eats("Pizza");
```

Let’s override the method `toString()` from the Object (Object class) class to
print a custom message. Every class in Dart extends from the base Object class.
```
String toString() {
return "My name is $name, and I like to eat $food";
}

12

Pragmatic Flutter

//Usage
print(child.toString());
//Output on console
My name is Krisha, and I like to eat Pizza
```

Cascading Syntax
Dart supports cascading syntaxes. It’s useful in assigning the values to properties
and methods at once using two dots.
```
child
. .name = 'Kalp'
. .eats("Pasta");
```

The setters can also be called using cascaded syntax as shown in the code snippet
below:
```
child
. .personName = 'Tanmay'
. .eats("Pesto");
```

Source Code Online
The source code for this example (Chapter01: Quick Reference to Dart2 (Classes))
is available at GitHub.

CONCLUSION
In this chapter, we reviewed the basic concepts and syntaxes useful to getting started
with developing Flutter application quickly and efficiently. You were introduced to
the structure of the Dart program. You developed your understanding of declaring
and using variables in Dart language. We explored methods to store data in collections using various data structures like List, Map, and Set. You also learned to write
reusable code using functions. Finally, you learned to architect and structure the
code base using Classes and methods.

REFERENCES
Dart Dev. (2020, 12 14). entries property. Retrieved from api.dart.dev: https://api.dart.dev/
stable/2.10.3/dart-core/Map/entries.html
Google. (2020, 11 13). A tour of the Dart language. Retrieved from Official Dart
Documentation: https://dart.dev/guides/language/language-tour

Dart Fundamentals

13

Google. (2020, 11 13). List<E> class. Retrieved from Official Dart Language Documentation:
https://api.dart.dev/stable/2.10.3/dart-core/List-class.html
Google. (2020, 11 13). Map<K, V> class. Retrieved from Official Dart Language
Documentation: https://api.dart.dev/stable/2.10.3/dart-core/Map-class.html
Google. (2020, 11 13). Object class. Retrieved from Official Dart Language Documentation:
https://api.dart.dev/stable/2.10.3/dart-core/Object-class.html
Google. (2020, 11 13). runtimeType property. Retrieved from Official Dart Documentation:
https://api.dart.dev/stable/2.10.2/dart-core/Object/runtimeType.html
Google. (2020, 11 13). Set<E> class. Retrieved from Official Dart Language Documentation:
https://api.dart.dev/stable/2.10.3/dart-core/Set-class.html
Google. (2020, 11 13). Spread Operator. Retrieved from Official Dart Language
Documentation: https://dart.dev/guides/language/language-tour#spread-operator
Moore, K. (2018, 08 07). Announcing Dart 2 Stable and the Dart Web Platform. Retrieved
from Medium: https://medium.com/dartlang/dart-2-stable-and-the-dart-web-platform3775d5f8eac7
Tyagi, P. (2020, 11 13). Chapter01: Quick Reference to Dart2 (Classes). Retrieved from
Pragmatic Flutter GitHub Repo: https://github.com/ptyagicodecamp/pragmatic_flutter/
blob/master/lib/chapter01/classes.dart
Tyagi, P. (2020, 11 13). Chapter01: Quick Reference to Dart2 (Collections). Retrieved from
Pragmatic Flutter GitHub Repo: https://github.com/ptyagicodecamp/pragmatic_flutter/
blob/master/lib/chapter01/collections.dart
Tyagi, P. (2020, 11 13). Chapter01: Quick Reference to Dart2 (Functions). Retrieved from
Pragmatic Flutter GitHub Repo: https://github.com/ptyagicodecamp/pragmatic_flutter/
blob/master/lib/chapter01/functions.dart
Tyagi, P. (2020, 11 13). Chapter01: Quick Reference to Dart2 (Variables & Data Types).
Retrieved from Pragmatic Flutter GitHub Repo: https://github.com/ptyagicodecamp/
pragmatic_flutter/blob/master/lib/chapter01/variables.dart

2

Introduction to Flutter

Flutter is an open-sourced software development kit (SDK) (Flutter) to develop
cross-platform applications and is free to use. It’s Google’s SDK for crafting
beautiful, fast, and natively compiled applications for mobile, web, and desktop from a single code base. Flutter applications are written in Dart language
(Dart). The Dart is optimized for building custom user interfaces (UIs) and fast
cross-platform applications. The Dart code compiles to Native machine code
for the platform app is running on. For example, the web Dart code compiles to
JavaScript. Flutter is a complete framework that provides UI rendering & widgets, state management solutions, navigation, testing, and hardware application
programming interfaces (APIs) to interact with device-level features like sensors, Bluetooth, etc.

CROSS-PLATFORM SOLUTIONS
The term ‘cross-platform solutions’ stands for the code reused across the different
platforms or ‘write code once and run everywhere’. The perfect cross-platform solution with a hundred percent code reuse is the holy grails that every mobile application developer dreams of. Let’s discuss some of the solutions used to maximize
the sharable code across multiple deployment targets like web, Android, iPhone
Operating System (iOS), and desktop.

Native SDKs
In the world of mobile app development, Native SDKs (Software development kit)
prominently refer to Apple’s iOS SDK (Develop iOS Applications) and Google’s
Android SDK (Develop Android Applications) to build mobile applications on iOS
and Android platforms, respectively. The iOS applications are developed using either
Objective-C (Objective-C) or Swift (Swift) programming languages. The Android
applications are developed using Java (Java) or Kotlin (A modern programming language that makes developers happier.) programming languages. Your app runs code
natively on the platform. The Native code is compiled to run on a particular platform
like Android or iOS.
In this architecture, as shown in Figure 2.1, the application ‘App-X’ talks to the
platform and accesses platform services directly. The platform side creates widgets
that are rendered on the screen’s canvas. The events are propagated back to the widgets. In this case, you would need to write two separate implementations of ‘App-X’
for each platform. Different implementations mean both apps are written in two
entirely different languages as well.
Android and iOS platforms support legacy (Objective-C for iOS and Java for
Android) and modern (Swift for iOS, and Kotlin for Android) programming
15

16

Pragmatic Flutter

FIGURE 2.1 Native platform architecture

languages to develop applications. To create the same application for Android
and iOS, a developer should be proficient in four programming languages all at
once. Things become more complicated if legacy and modern languages are used
together in the same code base. It may not be trivial to find developers who are
experts in all four languages simultaneously. As you can see, such scenarios are
not much cost-friendly. Since two separate applications need to keep the feature
parity, developers need to implement the same feature twice from scratch that can
take longer.
These are some of the issues that developers may want to avoid by using crossplatform solutions to develop applications that can share a single codebase in one
programming language.

JavaScript + WebView
One solution for developing cross-platform applications from a single code is to use
JavaScript with WebView(s). A WebView is a part of the browser’s engine that can be
inserted into a Native app along with loading web content in it.
In this architecture, as shown in Figure 2.2, the application ‘App-X’ creates
hypertext markup language (HTML) contents and displays them in a WebView on
the platform. The HTML/cascading style sheets (CSS) is used to recreate the Native
original equipment manufacturer (OEM) widgets. The app is written using a combination of JavaScript, HTML, and CSS. The platform’s services are accessed over
the JavaScript bridge. The ‘bridge’ does the context switches between the JavaScript
and the Native realms. It converts JavaScript instructions into Native instructions
and vice versa.
Some of the cross-platform frameworks that are based on this approach are
PhoneGap (Adobe) (Adobe PhoneGap), Apache Cordova, and Ionic. At the time of
this writing, Adobe discontinued investment in PhoneGap and Cordova.

Introduction to Flutter

17

FIGURE 2.2 JavaScript and WebView architecture

Reactive Native
In this approach, the creation of web views is simplified using design patterns based
on reactive programming (Reactive Programming). React Native solution was
developed by Facebook Inc. in 2005. It implements reactive style views on mobile
applications.
In this architecture, as shown in Figure 2.3, the JavaScript code communicates
with OEM widgets and platform services over the ‘bridge’. This bridge does the
context switching from the JavaScript realm to the Native realm and vice versa. This

FIGURE 2.3 React Native architecture

18

Pragmatic Flutter

FIGURE 2.4 Flutter architecture

context switching happens for every widget and platform-service request that can
cause performance issues and make sometimes widget rendering glitchy.

Flutter
The Flutter framework was developed by Google in 2017. Flutter is based on reactivestyle views like React Native. It doesn’t use bridges to talk to the platform and avoid
performance issues caused by the context switching from the JavaScript realm to the
Native realm. Flutter uses Dart language, which compiles ahead-of-time (AOT) into
Native code for multiple platforms.
In this architecture, as shown in Figure 2.4, it doesn’t require any JavaScript
bridge to communicate to the platform. The Dart source code compiles to Native
code, which runs on the Dart virtual machine. The Flutter comes with a vast library
of widgets for Material and Cupertino (for iOS) design specifications. The widgets
are rendered on the screen canvas, and events are sent back to widgets. ‘App-X’ talks
to platform services like Bluetooth, sensors, etc., using Platform Channels (Flutter
Platform Channels), which are way faster than the JavaScript bridges.

WHY FLUTTER
Now that you’re familiar with what Flutter has to offer (What’s Revolutionary about
Flutter), let’s look at some of the benefits that put Flutter ahead of its competitors.

Developer’s Productivity
The ‘Hot Reload’ (Hot reload) feature helps developers to move faster. This feature
allows developers to see the changes reflected at the interface as they write code in

Introduction to Flutter

19

real-time. There’s no time wasted in the long build-times to be able to check out the
changes made.

Front-end & Backend Using Dart
Flutter apps are written using the Dart language. The same programming language
can also be used to build the backend for the application. Developing front-end and
backend in the same language helps with the cost and developers’ familiarity with
both sides of the app development. The same developers can own the front-end as
well as the backend development that leads to lean and cost-effective development
cycles.

Dart Language
Flutter uses Dart language to write apps. It’s a delight to work with Dart language.
It is an object-oriented language that is built on the most popular features of other
reliable programming languages like Java and similar languages built upon objectoriented concepts. Dart is created, keeping developers in mind, and it is easy to learn
enough to start being productive from day one.

Human Interface Design
Flutter team implemented Material Design Specification (Material Foundation)
meticulously in Flutter. It makes easy to create slick, smooth, and crisp interfaces
for different platforms like Android and iOS. Flutter apps are compiled into Native
code for a platform that provides a Native feel on different platforms like Android,
iOS, Web, and Desktop.

Firebase Integration
Flutter’s integration with Firebase (Firebase Platform) is reliable. Firebase provides
the tools and services to support backend infrastructure instantaneously, which is
scalable and serverless. It comes with real-time databases, authentication, cloud storage, hosting, cloud-function, machine learning support.

Variety in IDE Support
Flutter offers multiple integrated development environment (IDE) to develop applications. As a Flutter developer, you have a choice between Android Studio (Google),
VS Code (Microsoft), IntelliJ IDEA (Jetbrains), and command line.

OEM Widget Independence
Flutter comes with its own suite of widgets that keep your app’s interface independent of changes in OEM widgets. OEM widgets come with devices and may look
different on different devices. The widgets solve this problem by providing a massive

20

Pragmatic Flutter

library of widgets for Material Design and iOS (Cupertino) (Cupertino (iOS-style)
widgets) platform, which helps in a seamless user experience regardless of which
device the app is running on.

Open Source/Community Support
Flutter and Dart are free to use open-source, and backed by a very active community
of developers worldwide. It’s easy to find support, resources, and technical knowhow on a topic. Flutter’s official documentation is fantastic and accepts contributions
from community members.

Cost-Effectiveness
Flutter helps developer in productivity while maintaining low development costs.
Flutter is not only used for developing user-facing front-end interfaces, but also solving backend problems. It provides support for code sharing from a single codebase.
Flutter apps are built once and deployed on multiple platforms like Android, iOS,
web, and desktop. You are not required to have separate teams to support them.

Custom Designs
Flutter is a great choice to build custom designs. It’s particularly useful when building designs for the app’s branding. Your brand design remains seamless across multiple platforms without worrying about the device. Additionally, it’s much faster to
develop prototypes that work cross-platform.

CONCLUSION
In this chapter, you were introduced about Flutter and how it compares to other
cross-platform alternatives. You learned about the different solutions available for
developing applications targeted to various platforms while maximizing the codereuse. You developed your understanding about Flutter’s features and benefits over
other cross-platform solutions.

REFERENCES
Adobe. (2020, 11 17). Adobe PhoneGap. Retrieved from PhoneGap: https://phonegap.com/
Apple. (2020, 11 16). Develop iOS Applications. Retrieved from Apple Developer: https://
developer.apple.com/develop/
Apple. (2020, 11 16). Swift. Retrieved from Apple Developer Documentation: https://
developer.apple.com/swift/
Dart Team. (2020, 11 17). Dart. Retrieved from Dart Website: https://dart.dev/
Develop Android Applications. (2020, 11 16). Retrieved from Android Developers: https://
developer.android.com/
Flutter Dev. (2020, 12 15). Hot reload. Retrieved from flutter.dev: https://flutter.dev/docs/
development/tools/hot-reload
Flutter Team. (2020, 11 17). Cupertino (iOS-style) widgets. Retrieved from Flutter
Documentation: https://flutter.dev/docs/development/ui/widgets/cupertino

Introduction to Flutter

21

Flutter Team. (2020, 11 17). Flutter. Retrieved from GitHub repository for Flutter SDK:
https://github.com/flutter
Google. (2020, 11 16). android studio. Retrieved from Android Developers: https://developer.
android.com/studio
Google. (2020, 11 17). Material Foundation. Retrieved from Material Design: https://
material.io/design
Google. (2020, 12 15). Firebase Platform. Retrieved from Firebase: https://firebase.google.
com/
JetBrains & Open-source Contributors. (2020, 11 16). A modern programming language that
makes developers happier. Retrieved from Kotlin Language: https://kotlinlang.org/
Jetbrains. (2020, 11 16). IntelliJ IDEA. Retrieved from Jetbrains: https://www.jetbrains.com/
idea/
Leler, W. (2017, 08 20). What’s Revolutionary about Flutter. Retrieved from hackernoon:
https://hackernoon.com/whats-revolutionary-about-flutter-946915b09514
Microsoft. (2020, 11 16). Visual Studio. Retrieved from code.visualstudio.com: https://code.
visualstudio.com/
Ravn, M. (2018, 08 28). Flutter Platform Channels. Retrieved from Medium: https://medium.
com/flutter/flutter-platform-channels-ce7f540a104e
Wikipedia. (2020, 11 16). Java. Retrieved from Wikipedia: https://en.wikipedia.org/wiki/
Java_(programming_language)
Wikipedia. (2020, 11 16). Objective-C. Retrieved from Wikipedia: https://en.wikipedia.org/
wiki/Objective-C
Wikipedia. (2020, 11 16). Reactive Programming. Retrieved from Wikipedia: https://
en.wikipedia.org/wiki/Reactive_programming
Wikipedia. (2020, 11 16). Software development kit. Retrieved from Wikipedia: https://
en.wikipedia.org/wiki/Software_development_kit

3

Setting Up Environment

This chapter gives a quick introduction to setting up a development environment
for developing Flutter applications. Flutter applications can be created in macOS,
Windows, Linux, and Chrome OS. In this chapter, setting up the environment on
macOS is covered. Please refer to the official documentation for setting up the environment on other operating systems here (Install).
The macOS supports developing Flutter apps for all four platforms: Android, iOS,
desktop macOS application, and web app in Chrome or Safari. Flutter’s desktop support allows it to compile Flutter source code to native macOS or Linux desktop apps.
However, a macOS Flutter desktop app can only be assembled on a Mac. A Linux
Flutter desktop app can only be compiled/developed on a Linux machine. In this book,
we’ll be building Flutter app examples for Android, iOS, Web, and macOS desktop
applications. You need at least one of the setups to be able to run your first Flutter app.
The Flutter is under rapid development itself, and some of the features like support to web and desktop are not rolled into stable release yet. The support for web
is available in ‘beta’ channel, and desktop support is available in ‘dev’ channel. You
may want to keep your Flutter channel to ‘dev’ when developing for web and desktop
at the same time. The ‘master’ channel has the bleeding edge improvements, features, and bug fixe. However, this channel is most unstable as well, and hence needs
to be avoided in production.

SYSTEM REQUIREMENTS FOR macOS
You need a 64-bit macOS with 2.8 GB disk space only for Flutter installation. Other
development tools and Integrated Development Environment (IDE) would require
additional disk space. You should be comfortable using command-line tools. Flutter
requires the following command-line tools preinstalled in your environment.
1.
2.
3.
4.
5.
6.

`bash`: Shell for macOS.
`which`: Unix based command to locate executables in the system.
`zip` & `unzip`: For compressing and decompressing files and directories.
`mkdir` & `rm`: For creating and removing directories and/or files.
git (version 2 or greater) (Download for macOS): Tool for version control.
curl (command line tool and library): Command line tool for data transfer.

Once you’ve all these tools installed and ready, it’s time to install the Flutter software
development kit (SDK) in your environment.

SETTING UP FLUTTER SDK
At the time of this writing, the Flutter SDK’s stable version for macOS is 1.22.4
(Flutter Stable 1.22.4). For the latest information about installing Flutter SDK, refer
23

24

Pragmatic Flutter

to the Flutter documentation (Get the Flutter SDK). You don’t need to worry about
installing Dart because Dart SDK is bundled with Flutter SDK.
In this section, we will briefly cover setting up Flutter SDK in the macOS environment. The Flutter is in active development, and a lot of changes are expected. Please
refer to the Flutter documentation to setup your Flutter environment for detailed and
latest information. I’m describing the installation process at a higher level, which is
less likely to change.

Download Stable Flutter SDK
It’s always a good idea to install the stable version for Flutter SDK to avoid unexpected behaviors. However, there’re many features related to web and desktop variants may not be available in the stable release. The good news is that you’re free to
change from one version of Flutter to another using Flutter channels.

Update PATH
Don’t forget to add Flutter SDK to your environment using `PATH (Update your
path). Once you’ve added the Flutter installation directory to your system’s `PATH`
variable, you can execute the `flutter` command from the terminal (bash).

Flutter Doctor
The `flutter doctor` command helps to find out if there are any required
dependencies that are not installed yet. If any dependency or tool is missing, it’ll let
you know about it and tell you how to do it.

Flutter Channels
Flutter channels are used to switch from one Flutter version to another. You can
choose to switch between different Flutter channels using command `flutter
channel` from the command line.
```
$ flutter channel
Flutter channels:
* master
dev
beta
stable
```

There are four channels at this time that you can choose from. You can switch to the
preferred channel using the command `flutter channel <channel _ name>`.
• `master`: You can switch to the master channel using command `flutter channel master`. It contains bleeding-edge changes. You may
need to switch to it to run some of the preview features. We may need to

Setting Up Environment

25

switch to this channel when demonstrating the latest and greatest features
that haven’t been released into stable channels yet.
• `dev`: This channel contains the latest fully-tested build. You can switch to
this channel using command `flutter channel dev`.
• `beta`: This channel contains the most stable dev build. It’s updated monthly.
You can switch to this channel using command `flutter channel beta`.
• `stable`: This channel contains the most stable beta build. It’s updated
quarterly. You can switch to this channel using command `flutter channel stable`.
After switching to your preferred channel, you need to run the command `flutter
upgrade` to bring in updates.

SETTING UP FOR THE ANDROID PLATFORM
Android Studio
Next step is to install Android Studio (Install Android Studio) along with the latest
Android SDK, Android SDK command-line tools, Android Build-tools.

Android Emulator
Create an emulator using Android Virtual Device (AVD) Manager in Android Studio
(Android Studio > Tools > AVD Manager). Create a virtual device by clicking on the
‘Create Virtual Device’ button. Choose hardware, system image (×64), and AVD
name for your emulator. Clicking on ‘Finish’ will create an AVD in the AVD manager. Click on the horizontal triangle icon to start it. Verify it by running command
`flutter devices` to see it in the device listing in the terminal.
You can also see device listing using the `flutter devices` command as below:
```
$ flutter devices
1 connected devices:
Android SDK built for x86 (mobile) • emulator-5554 •
android-x86 • Android 10 (API 29) (emulator)
```

Test Your Setup
Create a test project using `flutter create testapp`, and run it as below:
```
flutter create testapp
cd testapp
flutter run -d android
```

26

Pragmatic Flutter

FIGURE 3.1 TestApp running in Android

Refer to Figure 3.1 to see the default app running in the Android emulator.

Android Device
An Android device running Android 4.1 (API level 16) or higher is required to run a
Flutter app on an Android device. You would need to connect the device with a USB
cable to your computer to access it. Enable USB debugging (Configure on-device
developer options) on the Android device. Test the connection using the `flutter
devices` command. It should list the device on the console along with other connected devices, if any.

Setting Up Environment

27

Refer to Flutter Documentation (Android setup) for detailed Android setup
instructions.

SETTING UP FOR THE iOS PLATFORM
Xcode
Install the latest stable version of Xcode either from the Mac App Store (Xcode) or
the web (Xcode). Follow the prompts for installation. Xcode installation will install
command-line tools as well. Refer to Flutter documentation (Install Xcode) for
detailed instructions on installing and setting up Xcode.

iOS Simulator
On Mac, open the Simulator using command `open -a simulator`. At the time
of this writing, the default simulator is iPhone SE (2nd generation) (iPhone SE (2nd
generation)). Refer to documentation (Set up the iOS simulator) for detailed instructions on setting up an iOS simulator. You can also see device listing using the
`flutter devices` command as below:
```
$ flutter devices
2 connected devices:
Android SDK built for x86 (mobile) • emulator-5554
• android-x86 • Android 10 (API 29) (emulator)
iPhone SE (2nd generation) (mobile) • FCDB9B21-344C-4735-839493F0CF871DB2 • ios
•
com.apple.CoreSimulator.SimRuntime.iOS-13-5 (simulator)
```

Test Your Setup
Create a test project using `flutter create testapp`, and run it as shown
below using the simulator identifier. Alternatively, you can choose to run the command `flutter run` to run testapp on all connected platforms.
```
flutter create testapp
cd testapp
flutter run -d FCDB9B21-344C-4735-8394-93F0CF871DB2
```

Refer to Figure 3.2 to see the default app running in the Android emulator.

iOS Device
You can alternatively run the testapp on an iOS device. Follow the directions (Deploy
to iOS devices) to deploy to iOS devices. You would need to install a third-party

28

Pragmatic Flutter

FIGURE 3.2 TestApp running in iOS

dependency manager CocoaPods (CocoaPods) to manage dependencies. You also
need an Apple Developer account to run iOS apps on a device. Also, you need to
be enrolled in the Apple Developer Program (Apple Developer Program) to release
and distribute apps on the App Store. Refer to the setup directions (iOS setup) for
detailed iOS setup instructions.

SETTING UP FOR WEB
Flutter’s support for the Web is still in the early stages at the time of this writing.
Support for the web is available in the beta channel at this time. Switch to beta
channel using `flutter channel beta`. Don’t forget to run the `flutter
upgrade` command and enable web support.
```
flutter channel beta
flutter upgrade

Setting Up Environment

29

FIGURE 3.3 Android studio’s ‘Run’ toolbar showing chrome devices
flutter config --enable-web
```

Now that the web is enabled for your environment, you should see ‘Chrome (web)’
and ‘Web Server (web)’ listed in your Android Studio’s device listing section in the
top toolbar.
Refer to Figure 3.3 to see Android studio’s ‘Run’ toolbar showing chrome
devices.
You can also see device listing using the `flutter devices` command as
below:
```
$ flutter devices
2 connected devices:
Web Server (web) • web-server • web-javascript • Flutter Tools
Chrome (web)
• chrome
• web-javascript • Google Chrome
84.0.4147.89
```

Test Your Setup
Create a test project using `flutter create testapp`, and run it as below:
```
flutter create testapp
cd testapp
flutter run -d chrome
```

Refer to Figure 3.4 to see the default app running in the chrome browser.
Refer to Flutter documentation (Building a web application with Flutter) for
detailed web setup instructions.

SETTING UP FOR DESKTOP
Flutter’s support for the desktop is still in pre-early stages at the time of this writing. Support for the macOS and Linux desktop applications is available in the ‘dev’
channel at this time. Switch to ‘dev’ channel using `flutter channel dev`.
Don’t forget to run the `flutter upgrade` command and enable desktop support.

30

Pragmatic Flutter

FIGURE 3.4 TestApp running in chrome
```
$ flutter channel dev
$ flutter upgrade
//For macOS
$ flutter config --enable-macos-desktop
//For Linux
$ flutter config --enable-linux-desktop
```

Note: You’ll see Linux devices only on a Linux machine.
Now that desktop is enabled for your environment, you should see ‘macOS
(Desktop)’ in addition to ‘Chrome (web)’ and ‘Web Server (web)’ listed in your
Android Studio’s device listing section in the top toolbar.
Refer to Figure 3.5 to see Android studio’s ‘Run’ toolbar showing macOS(desktop)
and chrome devices.
You can also see device listing using the `flutter devices` command as
below:

FIGURE 3.5 Android Studio run toolbar showing macOS desktop and web devices in the
device listing

Setting Up Environment

31

```
$ flutter devices
3 connected devices:
macOS (desktop) • macos
• darwin-x64
• Mac OS X
10.15.6 19G73
Web Server (web) • web-server • web-javascript • Flutter Tools
Chrome (web)
• chrome
• web-javascript • Google Chrome
84.0.4147.105
```

Test Your Setup
Create a test project using `flutter create testapp`, and run it as below:
```
flutter create testapp
cd testapp
flutter run -d macos
```

Refer to Figure 3.6 to see the default app running in the macOS desktop application.
Refer to the documentation (Flutter Dev, 2020) for detailed desktop setup
instructions.

SOURCE CODE ONLINE
This app’s source code for all four platforms is available online at GitHub in the
‘testapp’ project (testapp).

FIGURE 3.6 TestApp running in macOS

32

Pragmatic Flutter

SETTING UP EDITOR
You can choose to build apps in Flutter using any editor or just command line
(Terminal in Mac) along with Flutter command-line tools. You also have the option
to choose the IDE of your choice along with Flutter editor plugins. The Flutter plugin
comes with productivity tools like syntax highlighting, easy and intuitive run and
debug support from IDE, etc. Few options of editors are Android Studio, IntelliJ,
Visual Studio Code, and Emacs. I’m choosing Android Studio to run the code snippets and examples in this book. I chose the Android Studio because it comes with all
the tools needed for Android development. You will need Xcode to prepare your iOS
app to distribute to App Store covered later in this book.

CONCLUSION
In this chapter, you got pointers for setting up the development environment on
MacOS. You got a high-level view of setting up a development environment for
building Flutter applications for Android, iOS, web, and desktop (macOS) platforms.
You learned to test platform setup for each of the platforms. You got an insight into
IDE options available for Flutter development as well.

REFERENCES
Android Developers. (2020, 12 14). Configure on-device developer options. Retrieved from
developer.android.com: https://developer.android.com/studio/debug/dev-options
Apple. (2020, 11 17). Xcode. Retrieved from Apple Apps: https://apps.apple.com/us/app/
xcode/id497799835
Apple. (2020, 11 17). Xcode. Retrieved from Apple Developer: https://developer.apple.com/
xcode/
Apple. (2020, 12 15). Apple Developer Program. Retrieved from developer.apple.com: https://
developer.apple.com/programs/
Cocoapods.org. (2020, 12 15). CocoaPods. Retrieved from cocoapods.org: https://cocoapods.
org/
Everything curl. (2020, 11 17). command line tool and library. Retrieved from Curl Website:
https://curl.se/
Flutter Dev. (2020, 11 17). Deploy to iOS devices. Retrieved from Flutter Dev: https://flutter.
dev/docs/get-started/install/macos#deploy-to-ios-devices
Flutter Dev. (2020, 11 17). Desktop support for Flutter. Retrieved from Flutter Development:
https://flutter.dev/desktop
Flutter Team. (2020, 11 17). Building a web application with Flutter. Retrieved from Flutter
Web: https://flutter.dev/docs/get-started/web
Flutter Team. (2020, 11 17). Flutter Stable 1.22.4. Retrieved from Download Flutter: https://
storage.googleapis.com/flutter_infra/releases/stable/macos/flutter_macos_1.22.4stable.zip
Flutter Team. (2020, 11 17). Get the Flutter SDK. Retrieved from Flutter Dev: https://flutter.
dev/docs/get-started/install/macos#get-sdk
Flutter Team. (2020, 11 17). Install. Retrieved from Flutter Dev: https://flutter.dev/docs/
get-started/install
Flutter Team. (2020, 11 17). Install Xcode. Retrieved from Flutter Dev: https://flutter.dev/
docs/get-started/install/macos#install-xcode

Setting Up Environment

33

Flutter Team. (2020, 11 17). iOS setup. Retrieved from Flutter Dev: https://flutter.dev/docs/
get-started/install/macos#ios-setup
Flutter Team. (2020, 11 17). Set up the iOS simulator. Retrieved from Flutter Dev: https://
flutter.dev/docs/get-started/install/macos#set-up-the-ios-simulator
Flutter Team. (2020, 11 17). Update your path. Retrieved from Flutter Dev: https://flutter.dev/
docs/get-started/install/macos#update-your-path
Git. (2020, 11 17). Download for macOS. Retrieved from Install Git: https://git-scm.com/
download/mac
Google. (2020, 11 17). Android setup. Retrieved from Flutter Dev: https://flutter.dev/docs/
get-started/install/macos#android-setup
Google. (2020, 11 17). Install Android Studio. Retrieved from Flutter Dev: https://flutter.dev/
docs/get-started/install/macos#install-android-studio
Priyanka Tyagi. (2020, 11 17). testapp. Retrieved from GitHub: https://github.com/
ptyagicodecamp/testapp
Wikipedia. (2020, 11 17). iPhone SE (2nd generation). Retrieved from Wikipedia: https://
en.wikipedia.org/wiki/IPhone_SE_(2nd_generation)

4

Flutter Project Structure

In this chapter, you’ll develop your understanding of the Flutter project’s structure.
We’ll be creating a Flutter app ‘Hello Books’ for demonstration. The ‘Hello Books’
app will display this greeting in three different languages: Spanish (Hola Libros),
Italian (Ciao Libri), and Hindi (हैल ो िकताब े )ं . The default greeting is displayed in the
English language. All other three greetings are stored in a List (List<E> class) data
structure. The app has a round button to select the greeting randomly from this list.
Figure 4.1 shows the finished ‘Hello Books’ app. Clicking on ‘Smiley’ icon
switches the greeting to a different language.

CHOOSING FLUTTER CHANNEL
We’ll be using the ‘dev’ channel to run the examples in this book since early support
for desktop along with support for web, Android, and iOS is available in this channel.
After switching to the ‘dev’ channel, don’t forget to run `flutter upgrade`. You
should see the following output on the console:
```
Flutter 1.21.0-1.0.pre • channel dev •
https://github.com/flutter/flutter.git
Framework • revision f25bd9c55c (2 weeks ago) • 2020-07-14
20:26:01 -0400

FIGURE 4.1

Hello Books App (Finished). Clicking on the ‘Smiley’ icon changes the greeting
35

36

Pragmatic Flutter

Engine • revision 99c2b3a245
Tools • Dart 2.9.0 (build 2.9.0-21.0.dev 20bf2fcf56)
```

You can run the `flutter channel` command to see the active channel marked
with ‘*’.
```
$ flutter channel
Flutter channels:
master
* dev
beta
stable
```

CREATING FLUTTER PROJECT
There are two ways to create Flutter projects: using command-line tools from
Terminal or using IDE. You can also create the project using the command line and
open it from IDE later on.

Using Command Line (terminal)
Run the following command to create a ‘hello_books’ project for the ‘Hello Books’
application.
```
$ flutter create hello_books
```

By default, the package structure is `com.example.hello _ books`. You can
specify your own package name using the command below when creating a project.
```
flutter create --org com.pragmatic_flutter hello_books
```

The above command would set Android’s package name and iOS bundle identifier to
`com.pragmatic_flutter.hello_books`.

You can open this project in Android Studio by clicking on the ‘Open an existing
Android Studio Project’ option on the launch screen, as shown in Figure 4.2.

Using IDE (Android Studio)
‘Start a New Flutter Project’ Screen
Start a new project by selecting this option on the launch screen as shown in Figure 4.3.

Flutter Project Structure

37

FIGURE 4.2 Android Studio launch screen displaying ‘Open an existing Android Studio
Project’ option

FIGURE 4.3 ‘Start a New Flutter Project’ screen

38

Pragmatic Flutter

FIGURE 4.4 ‘New Flutter Project’ screen

‘New Flutter Project’ Screen
This screen gives you the option to create a Flutter project, a Flutter module, package, or plugin. Since we’re creating a Flutter application, so choose the ‘Flutter
Application’ option as shown in Figure 4.4.
‘New Flutter Application’ Screen
Configure options for the new Flutter application on this screen shown in Figure 4.5.

FIGURE 4.5 ‘New Flutter Application’ screen (configuring project)

Flutter Project Structure

39

FIGURE 4.6 ‘New Flutter Application’ screen (setting package name)

Next, provide the package name to organize the source code. You also need to
select the support for ‘andoidx artifacts’ and Kotlin and Swift language support for
Android and iOS platforms as displayed in Figure 4.6.

CROSS-PLATFORM FLUTTER PROJECT STRUCTURE
The Flutter project has shared code in the ‘lib’ folder. Each platform has its own
folder to keep the platform-specific code. There are ‘android’, ‘iOS’, ‘web’, ‘linux’,
and ‘macOS’ folders for each platform Flutter app can be deployed to. The visual for
project structure is shown in Figure 4.7.
Let’s check out the details of significant project directories and files below:
• lib/: This folder contains all Dart files. This is a shared code across all
platforms like iOS, Web, Desktop, and embedded devices. In this book,
we’re focusing on Android, iOS, Web, and Desktop (macOS) only.
• android/: This folder contains native Android code, including
AndroidManifest.xml.
• ios/: This folder contains the iOS application’s native code in the Swift
language.
• web/: This folder includes ‘index.html’, assets that can be deployed to
the public hosting site.
• linux/: This folder contains the Linux platform-related code. This folder
is generated by enabling the support for desktop (Linux) but can only be
compiled on a Linux machine.
• macos/: This folder contains native code for the macOS platform.

40

Pragmatic Flutter

FIGURE 4.7 Flutter project structure in Android Studio

• test/: This folder contains all unit testing classes.
• pubspec.yaml: This is the dependency management and configuration
file for the Flutter application.

RUNNING DEFAULT APP: ANDROID, iOS, WEB, AND DESKTOP
In this section, we will run the ‘hello_books’ Flutter application on all four platforms:
Android, iOS, web, and desktop (macOS). Let’s run the ‘hello_books’ project on all
four platforms together using one simple command, ‘flutter run -d all’.

Android Platform
The Hello Books app running on Android emulator is shown in Figure 4.8.

iOS Platform
The Hello Books app running on iOS simulator is shown in Figure 4.9.

Web Platform
The Hello Books app running in Chrome browser is shown in Figure 4.10.

Flutter Project Structure

41

FIGURE 4.8 Hello Books running on Android emulator

Desktop (macOS) Platform
The Hello Books app running on macOS platform is shown in Figure 4.11.

Source Code Online
Source code for the ‘hello_books’ project is available at GitHub (Chapter04: Flutter
Project Structure (hello_books)).

RUNNING CODE SAMPLES
Flutter’s documentation is developer-friendly and easy to follow. It comes with a vast
library of sample code snippets. It provides the support to create Flutter applications
using sample code IDs and run it as a standalone Flutter app.

42

Pragmatic Flutter

FIGURE 4.9 Hello Books running on iOS simulator

Listing Sample Code IDs
The following command dumps the sample code identifiers/IDs in file ‘samples.json’.
```
flutter create --list-samples=samples.json
```

Contents of File ‘samples.json’
Below is a small snippet of the file. This particular sample code demonstrates the
usage of a ‘BottomAppBar’ widget and a docked ‘FloatingActionButton’
in it. You’ll learn about the widgets and building interfaces in upcoming chapters. The purpose of this section is to learn to explore Flutter’s official sample
code on your own.

Flutter Project Structure

FIGURE 4.10 Hello Books running on the web platform

FIGURE 4.11 Hello Books running on macOS platform

43

44

Pragmatic Flutter

```
[
{
"sourcePath": "lib/src/material/scaffold.dart",
"sourceLine": 1009,
"id": "material.Scaffold.3",
"channel": "master",
"serial": "3",
"package": "flutter",
"library": "material",
"element": "Scaffold",
"file": "material.Scaffold.3.dart",
"description": "This example shows a [Scaffold] with an
[AppBar], a [BottomAppBar] and a\n[FloatingActionButton]. The
[body] is a [Text] placed in a [Center] in order\nto center the
text within the [Scaffold]. The [FloatingActionButton]
is\ncentered and docked within the [BottomAppBar] using\
n[FloatingActionButtonLocation.centerDocked]. The
[FloatingActionButton] is\nconnected to a callback that
increments a counter.\n\n![](https://flutter.github.io/assetsfor-api-docs/assets/material/scaffold_bottom_app_bar.png)"
},
]
```

Creating Apps from Sample Code
Once you have got the sample id for the sample code, replace it in the following command. You also need to provide the name of the sample app that you’re importing
this code snippet into.
```
$ flutter create --sample=<id> <your_app_name>
```

Create an app for the sample id “material.Scaffold.3” using the above command as
below:
```
$ flutter create --sample=material.Scaffold.3
app_scaffold_demo
```

Once the project is created, go inside the project directory and run the app on all
targets.
```
$ cd app_scaffold_demo
$ flutter run -d all
```

Flutter Project Structure

45

FIGURE 4.12 Creating app from sample code ID (docked FloatingActionButton in
BottomAppBar widget)

App created using the sample code id ‘material.Scaffold.3’. This app shows
a docked ‘FloatingActionButton’ (FloatingActionButton class) in the
‘BottomAppBar’ (BottomAppBar class) widget as shown in Figure 4.12. We will
learn more about the Flutter application’s anatomy and widgets in the upcoming
chapters.

Source Code Online
Source code for the ‘app _ scaffold _ demo’ project is available at GitHub
(Chapter04: Flutter Project Structure).

USEFUL COMMANDS
Lastly, let’s reiterate the essential and useful commands used in Flutter development
as below:
• flutter doctor: Checks if your machine has all the needed packages
and software to build flutter apps.
• flutter create: Generates new flutter app.

46

Pragmatic Flutter

FIGURE 4.13 Available commands for Flutter

• flutter build: Builds flutter app.
• flutter run: Run flutter app on an attached device. It gives you the
option to select a device from the connected devices.
• flutter help: You can run ’flutter help’ in the command line
to list all other available commands. A screenshot of available commands
is shown in Figure 4.13.

CONCLUSION
In this chapter, you learned to create the Flutter project from the command line as
well as from the Android Studio IDE. You learned to open a preexisting Flutter
project from Android Studio. You learned about the Flutter release channels and
when to pick the ‘dev’ channel over the ‘stable’ or ‘beta’ channels. Finally, you also
learned how to create a Flutter project from sample code and run it. In the next
chapter (Chapter 05: Flutter App Structure), you’ll learn about the anatomy and app
structure of the ‘Hello Books’ Flutter application.

REFERENCES
Dart Team. (2020, 11 17). List<E> class. Retrieved from Dart Dev: https://api.dart.dev/
stable/2.8.4/dart-core/List-class.html
Flutter Dev. (2020, 11 17). BottomAppBar class. Retrieved from Flutter Dev: https://api.
flutter.dev/flutter/material/BottomAppBar-class.html
Flutter Dev. (2020, 11 17). FloatingActionButton class. Retrieved from Flutter Dev: https://
api.flutter.dev/flutter/material/FloatingActionButton-class.html
Tyagi, P. (2020, 11 17). Chapter04: Flutter Project Structure. Retrieved from Pragmatic
Flutter GitHub Repo: https://github.com/ptyagicodecamp/app_scaffold_demo
Tyagi, P. (2020, 11 17). Chapter04: Flutter Project Structure (hello_books). Retrieved from
Pragmatic Flutter GitHub Repo: https://github.com/ptyagicodecamp/hello_books
Tyagi, P. (2021). Chapter 05: Flutter App Structure. In P. Tyagi, Pragmatic Flutter: Building
Cross-Platform Mobile Apps for Android, iOS, Web & Desktop. CRC Press.

5

Flutter App Structure

In this chapter, you will develop your understanding of the Flutter application’s
structure using the HelloBooksApp from the previous chapter (Chapter 04: Flutter
Project Structure). The app starts displaying a greetings text ‘Hello Books’ in the
center of the device’s screen. This app will display this greeting in three different
languages: Spanish (Hola Libros), Italian (Ciao Libri), and Hindi (हैलो िकताबे )ं , in addition to the English language as the default. All other three greetings are stored in a
List (List<E> class) data structure `greetings`.
```
final List<String> greetings = [
'Hello Books',
'Hola Libros',
'Ciao Libri',
'हैलो िकताबें',
];
```

The app has a round floating button in the bottom right corner with a smiley icon to
select the next message from this list. Figure 5.1 shows transitioning from English
text to the next Spanish text. Each click on the smiley button will fetch the next message in the list. After reaching the last message in the list, it will resume from the
first message in the `greetings` list.

FIGURE 5.1 Finished HelloBooksApp
47

48

Pragmatic Flutter

FLUTTER WIDGETS
StatelessWidget
A StatelessWidget (StatelessWidget class) widget is immutable. Once it’s created, it can’t be changed. It doesn’t preserve its state. A stateless widget is created
only once, and it cannot be rebuild at a later time. Stateless widget’s 'build()'
method is called only once.
Let’s use the Container (Container Widget) widget to understand creating a
custom StatelessWidget. A container widget is a convenience widget that combines common painting, positioning, and sizing widgets.
The following code snippet demonstrates how a Container widget is created in
a stateless manner. This widget is created only once.
```
class MyStatelessWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container();
}
}
```

Stateless widgets don’t keep track of their state. Once they are created, their value
can’t be changed. If the value of the stateless widget needs to be changed, then new
widgets need to be created with the updated value. Some of the examples of Stateless
widgets are below:
• Text widget (Text Widget): It contains the immutable string of letters.
• Icon widget (Icon Widget): The icon widget is immutable and not meant
for interaction.
• Card widget (Card Widget): It is a material design card that is used to show
relevant information.
Figure 5.2 shows few examples of StatelessWidget.

FIGURE 5.2 Examples of StatelessWidget

Flutter App Structure

49

StatefulWidget
A StatefulWidget (StatefulWidget) widget is mutable. It keeps track of the state.
It rebuilds several times over its lifetime. A Stateful widget’s `build()` method is
called multiple times.
```
class MyStatefulWidget extends StatefulWidget {
@override
_MyStatefulWidgetState createState() =>
_MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
@override
Widget build(BuildContext context) {
return Container();
}
}
```

Some of the examples of Stateful widgets are below. They’re meant to keep track of
their state.
• Checkbox (Checkbox class): Keeps track of its state whether a checkbox
is checked or not.
• Radio (Radio<T> class): Needs to remember its state if it’s selected or not.
• TextField (TextField class): The TextField widgets enable users to type
in the text. That means it needs to keep track of what the user has already typed.
Figure 5.3 shows examples of StatefulWidget.
In the HelloBooksApp, we’ll use StatefulWidget to implement the ‘Smiley’
round button to change the greeting display text.

DISPLAY ‘HELLO BOOKS’ TEXT
We will start building the HelloBooksApp by displaying the ‘Hello Books’ text.
The app makes use of Material Design (Material Design). The MaterialApp

FIGURE 5.3 Examples of StatefulWidget

50

Pragmatic Flutter

(MaterialApp class) widget is used to implement material design. The class
`HelloBooksApp` extends `StatelessWidget`. A Flutter application is a stateless widget because it’s immutable. It can have mutable and immutable widgets as
its children. The `HelloBooksApp` widget implements the `build()` method of
parent `StatelessWidget`. The `build()` method is responsible for composing
the widgets to build the user interface. In this `build()` method, MaterialApp
widget is returned. The Text (Text class) widget is used to display the ‘Hello Books’
text. Let’s create a MaterialApp and display ‘Hello Books’ text in the code below:
```
class HelloBooksApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
//Text Widget without SafeArea
home: Text('Hello Books'),
);
}
}
```

The Flutter app during development has a debug banner at the top right corner.
You can remove it by setting the flag `debugShowCheckedModeBanner` in
MaterialApp to `false`.

Entry Point
We have HelloBooksApp ready to run on devices. We need to specify an entry point
where the compiler can start executing the app code. The `main()` method in most of
the programming languages is the method from which the compiler starts execution.
```
void main() {
runApp(HelloBooksApp());
}
```

Output
The text string ‘Hello Books’ is visible on the screen, as shown in Figure 5.4. You’ll
see the Text widget displaying ‘Hello Books’ aligned to the top of the screen.

Source Code Online
Source code for this example (Flutter App Structure: Display ‘Hello Books’ text) is
available at GitHub.

Flutter App Structure

51

FIGURE 5.4 ‘Hello Books’ displayed without SafeArea

ADD CUSHION AROUND THE TEXT
At this point, we have the text ‘Hello Books’ glued to the top of the screen. The
top part of the screen is used for showing system notifications. The Text widget
overlapping system notification is not a good design and usability decision. This
is where the SafeArea (Google, 2020) widget comes in handy. Wrapping Text
widget in SafeArea provides the safety padding to avoid the operating system level
notifications.
```
class HelloBooksApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: SafeArea(

52

Pragmatic Flutter
child: Text('Hello Books'),
),
);

}
}
```

Output
The ‘Hello Books’ text is padded from the top and provides enough space for the
operating system notifications.
Figure 5.5 shows the ‘Hello Books’ text rendered in a SafeArea widget.

Source Code Online
Source code for this example (Flutter App Structure: Add cushion around text) is available at GitHub.

FIGURE 5.5 ‘Hello Books’ displayed wrapped in SafeArea widget

Flutter App Structure

53

CENTER THE TEXT
Now that we have ‘Hello Books’ rendered with enough padding from the top, we want
to display text in the middle of the screen. The Center (Center class) widget centers its
child. Wrapping the Text (Text class) widget in the Center widget displays the ‘Hello
Books’ in the screen’s center.

Code
```
class HelloBooksApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: SafeArea(
child: Center(
child: Text('Hello Books'),
),
),
);
}
}
```

Output
The ‘Hello Books’ text is centered in the middle of the screen.
Refer to Figure 5.6 to see ‘Hello Books’ and its parent widget Center wrapped in
SafeArea widget.

Source Code Online
Source code for this example (Flutter App Structure: Center the text) is available at
GitHub.

APP ANATOMY #1
The HelloBooksApp is made of MaterialApp, SafeArea, Center, and Text widgets. The MaterialApp widget is at the root level. SafeArea widget is added as its
child. SafeArea widget’s child is Center, which wraps a Text widget in it. Figure 5.7
shows this relationship visually.

APP ANATOMY #2
Let’s improvise the app to look more like the finished app. We’ll be adding new widgets like Scaffold (Scaffold class), AppBar (AppBar class), and
FloatingActionButton (FloatingActionButton) next.
Figure 5.8 demonstrates the final version of Hello Books app.

54

Pragmatic Flutter

FIGURE 5.6 ‘Hello Books’ wrapped in SafeArea and Center widget. Center widget aligns
its child in the center of the screen

The Scaffold Widget
The MaterialApp widget is the starting point of the app. It’s used to inform Flutter
that the app is going to use material components (Components). Material components are interactive building blocks to create a user interface. The Scaffold widget is used as the child to MaterialApp widget. It implements the material design
basic visual layout structure and provides basic functionalities like app bar, floating
action button, etc., for the app.
```
class HelloBooksApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(),
);
}
```

Flutter App Structure

FIGURE 5.7 Anatomy#1 – Hello Books Flutter App

FIGURE 5.8 Anatomy#2 – Hello Books Flutter App

55

56

Pragmatic Flutter

The AppBar Widget
The AppBar (AppBar class) widget implements the material design app bar. It
assigns a title to the page using the `title` property.
```
class HelloBooksApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Hello Books'),
),
),
);
}
```

The FloatingActionButton Widget
The FloatingActionButton (FloatingActionButton class) widget implements the material design floating action button. The Scaffold widget’s
`floatingActionButton` property assigns FloatingActionButton to
the app. The smiley icon is implemented using the Icon widget as a child to
FloatingActionButton.
```
class HelloBooksApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () {},
tooltip: 'Greeting',
child: Icon(Icons.insert_emoticon),
),
),
);
}
```

Styling Text Widget
The MaterialApp comes with a built-in material design text theme. It can be
accessed using `Theme.of(context).textTheme` for the given widget. The
theme supports different sizes for text. We’re choosing `headline4` to style the
text. Themes are covered in detail in a later chapter (Chapter 10: Flutter Themes).

Flutter App Structure

57

```
class HelloBooksApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Text(
'Hello Books',
style: Theme.of(context).textTheme.headline4,
),
),
),
);
}
```

Complete Code
The HelloBooksApp code is ready to run. The full implementation is shown in the
code snippet below:
```
class HelloBooksApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: Text('Hello Books'),
),
body: Center(
child: Text(
'Hello Books',
style: Theme.of(context).textTheme.headline4,
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {},
tooltip: 'Greeting',
child: Icon(Icons.insert_emoticon),
),
),
);
}
}
```

58

Pragmatic Flutter

Source Code Online
Source code for this example (Flutter App Structure: App Anatomy#2) is available
at GitHub.

Managing State with StatefulWidget
We want to change the greetings text by clicking the smiley floating action button.
First, we need to store all the greetings in a list. Second, we need to enable the floating action button to pick the next available string from the list.
We need StatefulWidget to keep track of the current state of the selected
greeting. Let’s go ahead and create a StatefulWidget, say MyHomePage. This
widget is assigned as `home` to MaterialApp.
```
class HelloBooksApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
...
home: MyHomePage(title: 'Hello Books'),
);
}
}
```

StatefulWidget: MyHomePage
The Stateful widgets are useful when a part of the screen needs to be updated
with new information. In our app, we want to update the greeting text while rest of
the screen remains unchanged. The MyHomePage extends StatefulWidget and
accepts a title parameter. The widget has a mutable state and represented using
class ` _ MyHomePageState`.
```
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {}
```

State Widget: _ MyHomePageState
The widgets are rebuilt whenever the state change is requested from the `setState` (setState method) method. Let’s see how it’s done in HelloBooksApp. The

Flutter App Structure

59

FloatingActionButton is pressed by the user, which updates the currently
selected greeting to display on the screen.
```
class _MyHomePageState extends State<MyHomePage> {
//Spanish (Hola Libros), Italian (Ciao Libri), and Hindi
(हैलो िकताबें)
final List<String> greetings = [
'Hello Books',
'Hola Libros',
'Ciao Libri',
'हैलो िकताबें',
];
int index = 0;
String current;
void _updateGreeting() {
setState(() {
current = greetings[index];
index = index == (greetings.length - 1) ? 0 : index + 1;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Text(
greetings[index],
style: Theme.of(context).textTheme.headline4,
),
),
floatingActionButton: FloatingActionButton(
onPressed: _updateGreeting,
tooltip: 'Greeting',
child: Icon(Icons.insert_emoticon),
),
);
}
}
```

The `greetings` list contains greetings in four languages. The variable
`index` keeps the index of the currently selected item in the `greetings`
list. On pressing smiley floating action button or FAB calls ` _ updateGreeting` method. The ` _ updateGreeting` method updates currently selected
greeting text and updates `index` by one. The `index` is reset to zero when it
reaches the end of the list.

60

Pragmatic Flutter

Complete Code
The full implementation, including updating the text’s language, is in the code below:
```
//Entry point to the app
void main() {
runApp(HelloBooksApp());
}
class HelloBooksApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: MyHomePage(title: 'Hello Books'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
//Spanish (Hola Libros), Italian (Ciao Libri), and Hindi
(हैलो िकताबें)
final List<String> greetings = [
'Hello Books',
'Hola Libros',
'Ciao Libri',
'हैलो िकताबें',
];
int index = 0;
String current;
void _updateGreeting() {
setState(() {
current = greetings[index];
index = index == (greetings.length - 1)?
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),

0 : index + 1;

Flutter App Structure

61

),
body: Center(
child: Text(
greetings[index],
style: Theme.of(context).textTheme.headline4,
),
),
floatingActionButton: FloatingActionButton(
onPressed: _updateGreeting,
tooltip: 'Greeting',
child: Icon(Icons.insert_emoticon),
),
);
}
}
```

Source Code Online
Source code for this example (Flutter App Structure: HelloBooksApp) is available
at GitHub.

CONCLUSION
In this chapter, you learned about the Flutter application’s structure and anatomy.
You learned about the basic building blocks to build HelloBooksApp. We started
building the app by displaying the text on the screen. First you looked into the
bare minimum Flutter app’s anatomy. Then the app is improvised using material
components. The final HelloBooksApp included a FAB to pick a different greeting text from the list. You are also introduced to the basic Flutter widgets like
MaterialApp, Container, AppBar, Scaffold, FloatingActionButton,
Text, StatelessWidget, and StatefulWidget.

REFERENCES
Dart Dev. (2020, 11 17). List<E> class. Retrieved from Dart Dev: https://api.dart.dev/
stable/2.8.4/dart-core/List-class.html
Flutter Dev. (2020, 11 17). AppBar class. Retrieved from Flutter Dev: https://api.flutter.dev/
flutter/material/AppBar-class.html
Flutter Dev. (2020, 11 17). Card Widget