<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by saw lin on Medium]]></title>
        <description><![CDATA[Stories by saw lin on Medium]]></description>
        <link>https://medium.com/@linsaw49?source=rss-a3278f83f046------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Wc6Gt986cevQc7rk.jpg</url>
            <title>Stories by saw lin on Medium</title>
            <link>https://medium.com/@linsaw49?source=rss-a3278f83f046------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 12:50:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@linsaw49/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Flutter Complete Reference: Chapter 5]]></title>
            <link>https://medium.com/@linsaw49/flutter-complete-reference-chapter-5-b9c6beece3e4?source=rss-a3278f83f046------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9c6beece3e4</guid>
            <dc:creator><![CDATA[saw lin]]></dc:creator>
            <pubDate>Tue, 02 Aug 2022 17:06:46 GMT</pubDate>
            <atom:updated>2022-08-02T17:06:46.546Z</atom:updated>
            <content:encoded><![CDATA[<h3>Chapter 5. Inheritance and Exceptions<br>class B {}<br>class C extends A, B {}<br>When overriding a parameter’s type with a subtype, the compiler emits an error. Thanks to the<br>covariant keyword, you can turn off static analysis for this kind of error to tell the compiler you<br>know you’re doing this intentionally. Here’s an example:<br>abstract class Fruit {}<br>class Apple extends Fruit {}<br>class Grape extends Fruit {}<br>class Banana extends Fruit {}<br>abstract class Mammal {<br>void eat(Fruit f);<br>}<br>class Human extends Mammal {<br>// Ok<br>void eat(Fruit f) =&gt; print(“Fruit”);<br>}<br>class Monkey extends Mammal {<br>// Error<br>void eat(Banana f) =&gt; print(“Banana”);<br>}<br>Instead of eat(Banana f) we should have written eat(Fruit f) inside Monkey because the<br>superclass method is asking for Fruit. However, we can allow the definition of a subtype in an<br>overridden method with covariant:<br>class Monkey extends Mammal {<br>void eat(covariant Banana f) =&gt; print(“Banana”);<br>}<br>Now the code compiles. Usually the superclass method is the best place where you could use<br>covariant because it removes the “subtype constrain” along the entire hierarchy.<br>abstract class Mammal {<br>void eat(covariant Fruit f);<br>}<br>class Human extends Mammal {<br>// Ok<br>void eat(Fruit f) =&gt; print(“Fruit”);<br>Flutter Complete Reference</h3><p>107</p><p>Chapter 5. Inheritance and Exceptions<br>}<br>class Monkey extends Mammal {<br>// Ok<br>void eat(Banana f) =&gt; print(“Banana”);<br>}<br>Thanks to covariant Fruit at the top, any subclass is allowed to override eat() with Fruit or<br>a subtype. This keyword can also be applied to setters and fields.</p><p>5.1.1</p><p>super and constructors</p><p>Every subclass in Dart automatically tries to call the default constructor of the superclass. If<br>there isn’t one, you must call the superclass constructor manually in the initializer list.<br>class Example {<br>int a;<br>Example(this.a);<br>}<br>class SubExample extends Example {<br>int b;<br>// If you don’t call ‘super(b)’ the compilation will fail<br>// because the father class has NO default constructor<br>SubExample(this.b) : super(b);<br>}<br>The superclass constructor must be called in SubExample because the compiler has to somehow<br>initialize the variable a of Example. However super is not needed when the class has a default<br>constructor:<br>// The compiler automatically generates the default constructor<br>// which is just ‘Example();’<br>class Example {<br>int a = 0;<br>}<br>class SubExample extends Example {<br>int b;<br>// No need to call super<br>SubExample(this.b);<br>Flutter Complete Reference</p><p>108</p><p>Chapter 5. Inheritance and Exceptions<br>}<br>Which is equivalent to…<br>class Example {<br>int a = 0;<br>Example();<br>}<br>class SubExample extends Example {<br>int b;<br>SubExample(this.b) : super();<br>}<br>… but you shouldn’t do this because the compiler adds the missing pieces for you. You should<br>call the superclass constructor only when there are parameters to pass. The call to super(), in<br>case of an initializer list, always goes last:<br>// Compiles<br>MyClass(int a) : _a = a, super(a*a);<br>// Doesn’t compile<br>MyClass(int a) : super(a*a), _a = a;</p><p>5.1.2</p><p>Abstract classes</p><p>The abstract keyword defines a class that cannot be directly instantiated: only its derived<br>classes can. An abstract class can define one (or more) constructors as usual.<br>abstract class Example {<br>// This is an abstract method<br>void method();<br>}<br>Usually abstract classes contain abstract methods which can be defined putting a semicolon (;)<br>instead of the body. You cannot define an abstract method in a class that’s not been marked<br>with the abstract modifier.<br>// Wrong: doesn’t compile<br>class Example {<br>// This method is abstract (no body) BUT the<br>Flutter Complete Reference</p><p>109</p><p>Chapter 5. Inheritance and Exceptions</p><p>}</p><p>// class doesn’t have the ‘abstract’ modifier<br>void method();</p><p>// Correct: it compiles<br>abstract class Example {<br>// Good job, this abstract method is in an<br>// abstract class<br>void method();<br>}<br>If your class contains at least one method with no body, then it must be abstract and the<br>children must provide an implementation. You could also do this:<br>abstract class Example {<br>void method();<br>}<br>class ExampleTwo extends Example {}<br>ExampleTwo is an abstract class too because it doesn’t contain an implementation of method();<br>yet. A class is concrete (and thus not abstract) when every method has a body.<br>abstract class Example {<br>void method();<br>}<br>class ExampleTwo extends Example {<br><a href="http://twitter.com/override">@override</a><br>void method() {<br>print(“I’m not abstract!”);<br>}<br>}<br>Now ExampleTwo is a concrete class. As we’ve already said, getters and setters can also be<br>abstract and they’re declared in the same way as methods (without a body).<br>abstract class Example {<br>final int _a;<br>const Example(this._a);<br>Flutter Complete Reference</p><p>110</p><p>Chapter 5. Inheritance and Exceptions<br>// Abstract getter<br>int get calculate;</p><p>}</p><p>5.1.3</p><p>// Abstract method<br>int doSomething();</p><p>Interfaces</p><p>In contrast to other programming languages, Dart does not have an interface keyword and<br>you have to use classes to create interfaces. Your class can implement more than a single interface.<br>abstract class MyInterface {<br>void methodOne();<br>void methodTwo();<br>}<br>class Example implements MyInterface {<br><a href="http://twitter.com/override">@override</a><br>void methodOne() {}</p><p>}</p><p><a href="http://twitter.com/override">@override</a><br>void methodTwo() {}</p><p>The keyword is implements and, differently from a regular subclass, here you must override every method defined by the class/interface. The official documentation states the following:<br> Every class implicitly defines an interface containing all the instance members of<br>the class and of any interfaces it implements. If you want to create a class A that<br>supports class B’s API without inheriting B’s implementation, class A should implement the B interface.<br>In Dart when you use the term interface you are referring to a class that is going to be used<br>by others along with implements because it only provides method signatures. The concept is<br>the same you can find in Java, Delphi or C# with the only difference that Dart doesn’t have a<br>Flutter Complete Reference</p><p>111</p><p>Chapter 5. Inheritance and Exceptions<br>dedicated keyword.<br>// Instead of the ‘interface’ keyword, ‘abstract class’ is used<br>abstract class OneInterface {<br>void one();<br>}<br>abstract class TwoInterface {<br>void two();<br>}<br>class Example implements OneInterface, TwoInterface {<br><a href="http://twitter.com/override">@override</a><br>void one() {}</p><p>}</p><p><a href="http://twitter.com/override">@override</a><br>void two() {}</p><p>While extends can be used with only one class, implements works with one or more classes, which<br>you should treat as interfaces (methods with no body). You could also do the following:<br>class OneInterface {<br>void one() {}<br>}<br>class TwoInterface {<br>void two() {}<br>}<br>class Example implements OneInterface, TwoInterface {<br><a href="http://twitter.com/override">@override</a><br>void one() {}</p><p>}</p><p><a href="http://twitter.com/override">@override</a><br>void two() {}</p><p>Classes and abstract classes can both be treated as interfaces with the difference that in concrete<br>classes there must be at least an empty body. For this reason, in the above example we’ve put<br>Flutter Complete Reference</p><p>112</p><p>Chapter 5. Inheritance and Exceptions<br>an empty body.<br> We recommend to use abstract classes as interfaces so that you can write only<br>the name of the method, like void test();. If you used a regular class you’d have<br>to write void test() {} which is identical but it has an unnecessary empty body.</p><p>5.1.3.1</p><p>extends vs implements</p><p>You’ve just seen that extends is for subclasses and implements is for classes treated like if they<br>were interfaces. It would be very fair if you were puzzled about the situation. Let’s start with<br>the technical difference:<br>• When you use class B extends A {} you are NOT forced to override every method of<br>class A. Inheritance takes place and you can override as many methods as you want.<br>• When you use class B implements A {} you must override every method of class A.<br>Inheritance does NOT take place because methods just provide an API, a “skeleton” that<br>the subclass must concretize.<br>In practical terms instead:<br>• extends. This is the typical OOP inheritance that can be used when you want to add some<br>missing features in a subclass. In chapter 8 we will see that it’s a good practice deriving<br>only abstract classes and not concrete classes.<br>• implements. Interfaces are useful when you don’t want to provide an implementation of<br>the functions but just the API. It’s like if the interface was wall socket and the class was<br>the plug that adapts to the holes.<br>While multiple inheritance is not allowed, you can extends a class and implements more than<br>one. This is also how Java and C# behave, for example.<br>// Error<br>class A extends B, C, D {}<br>// Valid<br>class A extends B implements C, D {}<br>It might be useful if we made two final examples so that you can visualize the difference.<br>Flutter Complete Reference</p><p>113</p><p>Chapter 5. Inheritance and Exceptions<br>1. When you have a common behavior for every children of your hierarchy, create an abstract<br>class and use extends. Say that you want to read many popular document files such as<br>.pdf, .docx and .txt. Inheritance might be a very good idea:1<br>abstract class Reader {<br>bool fileExists(String path) {<br>// code…<br>}<br>double size(File file) {<br>// code…<br>}</p><p>}</p><p>String readContents();</p><p>Deciding whether a file exists or not and getting its size is something common we always<br>want to be able to call. Reading contents instead is specific to the implementation, it cannot<br>be shared along the hierarchy, so it has to be abstract.<br>class PDFReader extends Reader {<br><a href="http://twitter.com/override">@override</a><br>String readContents() {<br>// code…<br>}<br>}<br>class DocxReader extends Reader {<br><a href="http://twitter.com/override">@override</a><br>String readContents() {<br>// code…<br>}<br>}<br>class TxtReader extends Reader {<br><a href="http://twitter.com/override">@override</a><br>String readContents() {<br>// code…<br>1</p><p>See appendix A for more info on the File class</p><p>Flutter Complete Reference</p><p>114</p><p>Chapter 5. Inheritance and Exceptions</p><p>}</p><p>}</p><p>It’s been the right choice because fileExists() and size() have been defined only once,<br>so no code duplication, and they’re available in every subclass “for free”. If we used<br>implements we’d have had to define all of methods in the subclasses, including the “shared”<br>ones leading to code duplication.<br>2. When you don’t have methods implementations to share/reuse in the subclasses and you<br>just need to give the signature, use implements. Say that you want to create a few sorting algorithms by yourself: using interfaces is the way to go (this is known as “Strategy<br>pattern”).<br>// This is going to be the “interface”<br>abstract class Sorter {<br>void sort();<br>String averageComplexity();<br>}<br>class MergeSort implements Sorter {<br><a href="http://twitter.com/override">@override</a><br>void sort() {…}</p><p>}</p><p><a href="http://twitter.com/override">@override</a><br>String averageComplexity() =&gt; “n*log(n)”;</p><p>class InsertionSort implements Sorter {<br><a href="http://twitter.com/override">@override</a><br>void sort() {…}</p><p>}</p><p><a href="http://twitter.com/override">@override</a><br>String averageComplexity() =&gt; “n²”;</p><p>Any sorting algorithm has its own implementation and a particular name, so there’s no<br>common behavior. You just know that every concrete implementation needs a sorting<br>method (void sort()) and the average time complexity (String averageComplexity()).<br>Thanks to implements subclasses have to override every method and adopt a common API.<br>Flutter Complete Reference</p><p>115</p><p>Chapter 5. Inheritance and Exceptions<br>In summary, if you have common methods along the hierarchy go for subclasses otherwise use<br>classes as interfaces. The usage of implements forces you to override every method; if this is not<br>the behavior you’re looking for, use extends.</p><p>5.1.4</p><p>Mixins</p><p>There’s another important concept in Dart, which is the “cousin” of abstract classes and interfaces. A mixin is simply a class with no constructor that can be “attached” to other classes to<br>reuse the code without inheritance.<br>mixin Swimming {<br>void swim() =&gt; print(“Swimming”);<br>bool likesWater() =&gt; true;<br>}<br>mixin Walking {<br>void walk() =&gt; print(“Walking”);<br>}<br>If you use the special with keyword on a class, it acquires any method defined in the mixin. You<br>could see mixins like a “copy/paste” tool to reuse methods.<br>class Human with Walking {<br>final String _name;<br>final String _surname;</p><p>}</p><p>Human(this._name, this._surname);<br>void printName() =&gt; “$_name $_surname”;</p><p>void main() {<br>final me = Human(“Alberto”, “Miola”);</p><p>}</p><p>// prints “Alberto Miola”; method is defined in the class<br>me.printName();<br>// prints “Walking”; method is not defined in the class<br>// but it’s “copied” and “pasted” from the mixin.<br>me.walk();</p><p>Flutter Complete Reference</p><p>116</p><p>Chapter 5. Inheritance and Exceptions<br>The class Human doesn’t have a walk() method inside but it’s automatically imported from the<br>Walking mixin. Since mixins are just classes without a constructor, you could also successfully<br>compile the following code:<br>// use ‘class’ instead of ‘mixin’<br>class Walking {<br>void walk() =&gt; print(“Walking”);<br>}<br>class Human with Walking {}<br>In general it’d better if you used the mixin keyword since it helps both yourself, to remind what<br>you want to do, and the IDE, which can give you useful hints. Furthermore, using the mixin<br>keyword is less confusing than class.<br> Note that your class must have no constructors declared in order to be used as<br>mixin.<br>class Walking {<br>Walking();<br>void walk() =&gt; print(“Walking”);<br>}<br>// Does not compile<br>class Human with Walking {}<br>Even if you’ve declared the empty non-argument constructor (Walking()) this class<br>is not treated as a mixin. You should prefer mixin over class when you intend to<br>accomplish this purpose.<br>Some other important features offered by mixins are:<br>1. A class can have more than a single mixin associated to it and its subclasses inherit the<br>imported methods.<br>mixin Walking {<br>void walk() {}<br>}<br>mixin Breathing {<br>void breath() {}<br>Flutter Complete Reference</p><p>117</p><p>Chapter 5. Inheritance and Exceptions<br>}<br>mixin Coding {<br>void code() {}<br>}<br>// Human only has walk()<br>class Human with Walking {}<br>// Developer has walk() inherited from Human and also<br>// breath() and code() from the two mixins<br>class Developer extends Human with Breathing, Coding {}<br>2. There’s the possibility to constrain the usage of a mixin to subclasses of a certain type. In<br>this way you can make a sort of “restrictive reusability”:<br>// Constrain ‘Coding’ so that it can be attached only to<br>// subtypes of ‘Human’<br>mixin Coding on Human {<br>void code() {}<br>}<br>// All good<br>class Human {}<br>class Developer extends Human with Coding {}<br>// NO, ‘Coding’ can be used only on subclasses<br>class Human with Coding {}<br>// NO, ‘Fish’ is not a subclass of ‘Human’ so<br>// you cannot attach the ‘Coding’ mixin<br>class Fish with Coding {}<br>Mixins are different from abstract classes and interfaces because they do not involve inheritance<br>at all: they don’t create hierarchies. They are just a way to reuse code without having to deal<br>with superclasses, overrides and so on.<br> There is no rule of thumb to follow when it comes to the question “when should<br>I prefer mixins over interfaces/abstract classes?” because the answer would be “It<br>depends!”. However, here’s a general idea that you can follow to take your decision.<br>Flutter Complete Reference</p><p>118</p><p>Chapter 5. Inheritance and Exceptions</p><p>In general your first choices should be abstract classes or interfaces, with all their implementations<br>in the various subclasses. Mixins are very handy when different pieces of architecture have the<br>same identical code which cannot be shared due to a lack of inheritance. Let’s say you have these<br>classes in a folder:<br>import ‘dart:math’;<br>abstract class FootballTeam {<br>String name();<br>void playsWith() =&gt; print(“Ball”);<br>double ballVolume(double radius) {<br>const values = 4/3 * 3.14;<br>return values * pow(radius, 3);<br>}<br>}<br>class RealMadrid extends FootballTeam { … }<br>class LiverpoolFC extends FootballTeam { … }<br>And then, still in the same project, you have in another folder this hierarchy:<br>abstract class VolleyballTeam {<br>String nameAndAbbreviation();<br>void playsWith() =&gt; print(“Ball”);<br>double ballVolume(double radius) {<br>const values = 4/3 * 3.14;<br>return values * pow(radius, 3);<br>}<br>}<br>class TeamA extends VolleyballTeam { … }<br>class TeamB extends VolleyballTeam { … }<br>You see two separated hierarchies (which is good) with a few identical methods. You could<br>create a superclass for VolleyballTeam and FootballTeam but it couldn’t be possible due to the<br>structure itself of your architecture. A good solution is the usage of a mixin which provides code<br>sharing with no inheritance.<br>mixin BallSports {<br>Flutter Complete Reference</p><p>119</p><p>Chapter 5. Inheritance and Exceptions<br>void playsWith() =&gt; print(“Ball”);</p><p>}</p><p>double ballVolume(double radius) {<br>const values = 4/3 * 3.14;<br>return values * pow(radius, 3);<br>}</p><p>At this point you can get rid of the redundant methods and use the mixin to share the implementation (across the hierarchy as well). In this way you’ve removed code duplication, which is<br>always a problem in terms of maintenance.<br>// Somewhere in your project…<br>abstract class FootballTeam with BallSports {<br>String name();<br>}<br>// Somewhere else in your project…<br>abstract class VolleyballTeam with BallSports {<br>String nameAndAbbreviation();<br>}<br>No more code duplication because the mixin solved the problem. Both hierarchies are separated<br>because they are two different things but they have something in common. A mixin makes<br>methods reusable without having to rely on inheritance.</p><p>5.1.5</p><p>Good practices</p><p>Generally, factory constructors are used to return “default” implementations of a certain class.<br>For example, if you had a series of encryption algorithms, you could define a default one in this<br>way:<br>abstract class EncryptionAlgo {<br>// ‘AESEncryption’ is the default encryption algorithm<br>factory EncryptionAlgo() {<br>return AESEncryption();<br>}</p><p>}</p><p>void decrypt(String filePath);</p><p>Flutter Complete Reference</p><p>120</p><p>Chapter 5. Inheritance and Exceptions</p><p>class AESEncryption extends EncryptionAlgo { … }<br>class RSAEncryption extends EncryptionAlgo { … }<br>class BlowfishEncryption extends EncryptionAlgo { … }<br>With this technique, you can use EncryptionAlgo to return an instance of AESEncryption:<br>// ‘encrypt’ is actually ‘AESEncryption’ because you’re calling the<br>// factory constructor<br>final encrypt = EncryptionAlgo();<br>You are NOT creating an instance of an abstract class (which is impossible): you’re just calling<br>the factory constructor of EncryptionAlgo which returns a AESEncryption. This technique<br>is used to return “default” instances of a certain hierarchy. You could use an even shorter<br>syntax:<br>abstract class EncryptionAlgo {<br>factory EncryptionAlgo() = AESEncryption;</p><p>}</p><p>void decrypt(String filePath);</p><p>This kind of constructor assignment is just a shorter syntax to redirect a constructor to another.<br>However, they must have the same number and type of arguments otherwise it won’t compile.<br>Basically you’re telling the compiler to call the constructor of AESEncryption (along with the<br>params, if any) when the factory is invoked.</p><p>5.2</p><p>Extension methods</p><p>Starting from Dart 2.7 the team has added extension methods, a way to add functionalities to<br>a library knowing nothing about its internal implementation. Let’s take a look at the String<br>class, which has a lot of methods:<br>// A string<br>var name = “Alberto”;<br>// Some methods of the string class<br>name.toUpperCase();<br>name.toLowerCase();<br>name.trimLeft()<br>Flutter Complete Reference</p><p>121</p><p>Chapter 5. Inheritance and Exceptions<br>Earlier we worked hard to create a Fraction class and it would be really cool if we were able to<br>integrate it with strings. Something like this:<br>final Fraction value = “1/3”.toFraction();<br>value.reduce();<br>value.negate();<br>Given a string, we could add the toFraction() method that returns a Fraction whenever<br>possible. We don’t have access to the String class and we can not edit the file in which it’s been<br>declared, of course. Extension methods come to the rescue:<br>extension FractionExt on String {<br>bool isFraction() =&gt; …</p><p>}</p><p>// Converts a string into a fraction<br>Fraction toFraction() =&gt; Fraction.fromString(this);</p><p>The this identifier refers to the object on which you are calling the method. What’s written as<br>this.contains(“/”) is evaluated to “2/5”.contains(“/”) is the example:<br>extension FractionExt on String {<br>// code…<br>}<br>void main() {<br>var str = “2/5”;</p><p>}</p><p>if (str.isFraction()) {<br>final frac = str.toFraction();<br>}</p><p>With extension methods we’ve just extended the String class with new functionalities without<br>changing the definition of the class. Methods have been added “from the outside”.<br> Abstract classes, interfaces and mixins are for “internal use” in the sense that with<br>them you touch the class directly from the inside. Extensions are for “external use”<br>in the sense that you add methods from the outside without changing the internal<br>Flutter Complete Reference</p><p>122</p><p>Chapter 5. Inheritance and Exceptions<br>part of the class.<br>With extensions you can also define getters, setters, operators, static fields and/or methods. If<br>you need to use some utility private functions inside the extension, just append an underscore<br>(_) in front of the name. It’s like with classes, where void _method() {} is private to its library.<br> Extension methods also work with generic types. You could for example write<br>extension Test&lt;T&gt; on List&lt;T&gt; {} where T is statically determined by the compiler. Generics and collections will be discussed in the next chapter.</p><p>5.2.1</p><p>Good practices</p><p>Generally extension methods should be put in a dedicated file. For example, the previous extension of fraction could go on fraction_ext.dart so that it can be imported as a library.<br>// === file fraction_ext.dart === //<br>extension FractionExt on String {<br>// code…<br>}<br>// === file main.dart === //<br>import ‘package:fraction_ext.dart’;<br>void main() {<br>final check = “hello”.isFraction();<br>}<br>Short and trivial operations should be implemented with extensions in order to improve the<br>usability, the readability. Don’t you agree that…<br>final f = “1/2”.isFraction();<br>… looks better than a static method call?<br>final f = Fraction.isFraction(“1/2”);<br>Keep in mind that extension methods cannot be used if you’re treating a variable with dynamic.<br>They support type inference and then the compiler must always exactly know the types.<br>// It compiles but gives a runtime exception<br>Flutter Complete Reference</p><p>123</p><p>Chapter 5. Inheritance and Exceptions<br>dynamic f = “1/2”;<br>f.isFraction();<br>Before moving on, let’s try to make a simple summary of all the features we’ve seen up to now<br>in this chapter.<br>• Internal use. These techniques are meant for “internal use” because they can work directly<br>inside the definition of the class.<br>– extends. It’s the typical OOP inheritance: you don’t need to override every method,<br>getter or setter. Use it when there is a “common” behavior to share along the hierarchy.<br>– implements. The “interface” OOP concept: you need to override every method, getter<br>or setter. Use it when you want to define an API for many types (they have no common<br>behaviors to share).<br>– mixin. A way to “copy/paste” methods into classes: they reduce code duplication<br>and centralize the code. The imported methods are also shared along the hierarchy.<br>• External use. These techniques are meant for “external use” because they cannot modify<br>the class from the inside.<br>– extension. They add functionalities to a class without changing its internal definition.<br>They’re generally used to “improve” a class without touching its internals.</p><p>5.3</p><p>The Object class</p><p>Even if it’s not explicitly written in the code, any Dart class descends from class Object {}<br>which is at the root of any hierarchy. This is the same structure that some popular languages<br>such as Java, C# and Delphi adopt. Every class can, and should, override the methods declared<br>in Object.<br>• String toString(). This method is very important and you should always override it<br>because a string representation of an object is quite handy, especially while debugging. If<br>you have it defined you can better handle the string conversion:<br>final f = Fraction(1, 2);<br>final s = “My fraction is $f”;<br>String interpolation automatically calls toString() which makes the code shorter and more<br>readable.<br>Flutter Complete Reference</p><p>124</p><p>Chapter 5. Inheritance and Exceptions<br>• bool operator ==(SomeClass other). When you want to compare two objects you have<br>to use the == operator. By default it doesn’t really work as you’d expect; it returns true<br>only if two variables point to the same object.<br>class Example {<br>int a;<br>Example(this.a);<br>}<br>void main() {<br>final ex1 = Example(2);<br>final ex2 = ex1;<br>print(ex1 == ex2); //true<br>}<br>The console outputs true because ex2 points to the same reference held by ex1; both<br>variables point to the same object so they’re equal. By default the == operator compares<br>references and doesn’t look at the object itself; it only cares about what’s being pointed to.<br>void main() {<br>final ex1 = Example(2);<br>final ex2 = Example(2);<br>print(ex1 == ex2); //false<br>}<br>Logically we’d think they were equal but the compiler tells us another story. ex1 and ex2<br>point to two different objects that are logically equal but practically different because each<br>variable holds a different reference. You have to override the equality operator to get the<br>desired behavior:<br>class Example {<br>int a;<br>Example(this.a);<br><a href="http://twitter.com/override">@override</a><br>bool operator ==(Object other) {<br>// 1.<br>if (identical(this, other))<br>return true;<br>Flutter Complete Reference</p><p>125</p><p>Chapter 5. Inheritance and Exceptions<br>// 2.<br>if (other is Example) {<br>final example = other;</p><p>}</p><p>}</p><p>// 3.<br>return runtimeType == example.runtimeType &amp;&amp;<br>a == example.a;<br>} else {<br>return false;<br>}</p><p>// 4.<br><a href="http://twitter.com/override">@override</a><br>int get hashCode =&gt; a.hashCode;</p><p>That’s a lot of boilerplate code but you don’t have any other choices. For sure if you come<br>from the Java world you might have dealt with this exact same thing thousands of times.<br>1. The function identical() is provided by the Dart code API and checks if two objects<br>have the same reference.<br>2. If the type of the compared object is equal to the type of the current object, a smart cast<br>happens in the body to proceed with the comparison. Otherwise, false is returned.<br>3. Check if the runtime types are the same and then make a one by one comparison for<br>every instance variable.<br>4. See the next point.<br>Those two overrides allow a proper object comparison as you’d expect. Running this example would output true because we’ve taught operator== to look at the object itself and<br>not only at the references.<br>void main() {<br>final ex1 = Example(2);<br>final ex2 = Example(2);<br>print(ex1 == ex2); // true -&gt; that’s what we wanted!<br>}<br>• int get hashCode. When you override the equality operator, you must always remember<br>Flutter Complete Reference</p><p>126</p><p>Chapter 5. Inheritance and Exceptions<br>to also override hashCode. The hash code is useful when you call the identical() method<br>and also when you use “hash maps” we’re going to analyze in the next chapter.<br>If you know what hash tables are, you are aware that the keys must not clash in order to<br>keep good performances. Dart’s implementation of hash tables guarantees O(1) in insertion<br>if hash codes of different objects return different values (no collisions).</p><p>5.3.1</p><p>Comparable&lt;T&gt;</p><p>Other than overriding operator== and hashCode, if you wanted to do a precise and complete<br>comparison setup of a class, you should also implement Comparable&lt;T&gt;. This is how a complete<br>comparison logic for a Fraction class would look like:<br>class Fraction implements Comparable&lt;Fraction&gt; {<br>final int num;<br>final int den;<br>const Fraction(this.num, this.den):<br>double toDouble() =&gt; num / den;<br><a href="http://twitter.com/override">@override</a><br>int compareTo(Fraction other) {<br>if (toDouble() &lt; other.toDouble()) return -1;<br>if (toDouble() &gt; other.toDouble()) return 1;<br>return 0;<br>}<br><a href="http://twitter.com/override">@override</a><br>bool operator==(Object other) { … };</p><p>}</p><p><a href="http://twitter.com/override">@override</a><br>int get hashCode { … };</p><p>Comparable&lt;T&gt; exposes the compareTo() method which can be used for ordering and sorting.<br>The returned int value must follow this convention:<br>• if this instance is naturally &lt; than the other, return a negative number;<br>• if this instance is naturally &gt; than the other, return a positive number;<br>Flutter Complete Reference</p><p>127</p><p>Chapter 5. Inheritance and Exceptions<br>• if the two instances are equal, return 0.<br>Returning 1 and -1 is just a convention; it can be any positive or negative number. In our case,<br>we have done the following:<br>• a fraction is naturally &lt; than another if its double representation is smaller than the other.<br>For this reason, we return -1 in case the num / den ratio of the current instance were &lt;<br>than the other.<br>if (toDouble() &lt; other.toDouble()) return -1;<br>• a fraction is naturally &gt; than another if its double representation is greater than the other.<br>For this reason, we return 1 in case the num / den ratio of the current instance were &gt;<br>than the other.<br>if (toDouble() &gt; other.toDouble()) return 1;<br>• two fractions are equal if the rational number they represent is also equal. For this reason,<br>we return 0 if none of the above statements passed.<br>return 0;<br>In general, comparing floating point numbers using &lt;, &lt;=, &gt; and &gt;= is safe. Comparing floating<br>point values with operator== is very error prone; two values that should be equal may not be<br>due to arithmetic rounding errors. This is the reason why we use return 0 as “fallback” rather<br>than checking for equality of double values.</p><p>5.4</p><p>Exceptions</p><p>Dart code can throw exceptions to signal that an unexpected or erroneous behavior has happened<br>during the execution. When you throw an exception you should really catch it otherwise your<br>program will forcefully terminate with an error code.<br>class Fraction {<br>int _numerator;<br>int _denominator;<br>Fraction(this._numerator, this._denominator) {<br>if (_denominator == 0) {<br>throw IntegerDivisionByZeroException();<br>}<br>}<br>Flutter Complete Reference</p><p>128</p><p>Chapter 5. Inheritance and Exceptions</p><p>}<br>The denominator of a fraction cannot be zero and in our example the constructor is the best place<br>to throw an exception. It signals that something’s gone wrong, in this case an invalid parameter.<br>You can only throw objects.<br> The IntegerDivisionByZeroException() class is provided by Dart and it should<br>be used when… a division by zero happens! Despite you can throw any object, classes<br>with meaningful names should be preferred.<br>class RandomClass() {}<br>void main() {<br>// It compiles. It’s perfectly fine<br>throw RandomClass();<br>}<br>You could also throw a single string like throw “Whoops”; because String is a Dart<br>class.<br>There are a few interchangeable classes that can be thrown in exceptions. For sure, if you have<br>a format error you’re not going to throw a TimeoutException.<br>• DeferredLoadException<br>• FormatException<br>• IntegerDivisionByZeroException<br>• IOException<br>• IsolateSpawnException<br>• TimeoutException<br>You can throw everything except for null.</p><p>5.4.1</p><p>on and catch</p><p>If you don’t catch an exception, your program forcefully terminates but you never want to be in<br>such situation. It’s always a good idea handling exceptions by catching them.<br>Flutter Complete Reference</p><p>129</p><p>Chapter 5. Inheritance and Exceptions<br>void main() {<br>try {<br>final f = Fraction(1, 0);<br>} on IntegerDivisionByZeroException {<br>print(“Ouch! Division by zero!”);<br>}<br>}<br>This code is safe because the exception raised by the constructor of Fraction is caught by a try<br>block. If you want to get an instance of the thrown exception, just add a catch statement:<br>void main() {<br>try {<br>final f = Fraction(1, 0);<br>} on IntegerDivisionByZeroException catch (exc) {<br>// use the exc object<br>doSomething(exc);</p><p>}</p><p>}</p><p>print(“Ouch! Division by zero!”);</p><p>exc is an instance of the thrown object that can only be used within the scope of on. This<br>approach can be useful when there’s the need to print a stack trace or any useful debugging info<br>about the exception.<br>void main() {<br>try {<br>final f = Fraction(1, 0);<br>} on IntegerDivisionByZeroException {<br>print(“Division by zero!”);<br>} on FormatException {<br>print(“Invalid format!”);<br>}<br>}<br>You can handle code that could throw more than a single exception by specifying multiple catch<br>clauses. The first clause that matches the thrown object will be picked to handle the error<br>propagation. What if the above code threw an IOException or another object you haven’t<br>handled? The program would crash because there would be a not handled exception.<br>Flutter Complete Reference</p><p>130</p><p>Chapter 5. Inheritance and Exceptions<br>void main() {<br>try {<br>final f = Fraction(1, 0);<br>} on IntegerDivisionByZeroException {<br>print(“Division by zero!”);<br>} on FormatException {<br>print(“Invalid format!”);<br>} catch (e) {<br>// You arrive here if the thrown exception is neither<br>// IntegerDivisionByZeroException or FormatException<br>print(“General error: $e”);<br>}<br>}<br>The final catch is a fallback that captures everything else that didn’t match the above types.<br>You’re guaranteed that this code is safe because, worst case, the two on will be skipped and the<br>execution will fall inside the final catch.</p><p>5.4.2</p><p>finally</p><p>The try — catch block protects your code against runtime exceptions that alter the normal<br>execution flow. As you know, if no exceptions occur nothing happens because the catch block<br>doesn’t execute.<br>void main() {<br>try {<br>final f = Fraction(2, 3);<br>} catch (e) {<br>print(“Error”);<br>}</p><p>}</p><p>print(“Finish”);</p><p>This simple code only outputs “Finish” because no exceptions have been thrown. However,<br>there is a way to force the execution of a part of the try statement.<br>void main() {<br>try {<br>final f = Fraction(2, 3);<br>Flutter Complete Reference</p><p>131</p><p>Chapter 5. Inheritance and Exceptions<br>} catch (e) {<br>print(“Error”);<br>} finally {<br>print(“Always here”);<br>}</p><p>}</p><p>print(“Finish”);</p><p>The body of a finally block is always executed, no matter if an exception occurs or not. The<br>above code prints “Always here” and then “Finish” on a new line.<br>• The code inside on or catch is executed only if an exception is thrown and a valid handler<br>for the object is provided. If no exceptions are thrown, nothing happens.<br>• The code inside a finally block is always executed regardless the fact that an exception<br>object is thrown or not.</p><p>5.4.3</p><p>Good practices</p><p>The Dart API provides the Exception interface which is implemented by all core library exceptions. Production-quality code usually throws subtypes implementing one of the following<br>classes.<br>• Exception. Implement this interface to create errors that will be caught when something<br>goes wrong. For example, doing this is a good idea:<br>class FractionDivisionByZero implements Exception {<br>final String message;<br>const FractionDivisionByZero(this.message);</p><p>}</p><p><a href="http://twitter.com/override">@override</a><br>String toString() =&gt; message;</p><p>We can throw the class FractionDivisionByZero specific object rather than a general<br>purpose IntegerDivisionByZeroException. When you have to throw an object, implement Exception and choose a proper name that describes what’s gone wrong.</p><p>Flutter Complete Reference</p><p>132</p><p>Chapter 5. Inheritance and Exceptions<br> The official documentation 2 suggests to not use throw Exception(“…”);.<br>Yes, you could, but it’s bad because it doesn’t give a precise type that can be<br>caught with the on keyword.<br>• Error. You should subclass this type for all those programmer-relates errors such as going<br>out from the bounds of a list or having an assertion that evaluates to false. Error is thrown<br>in case of an unexpected program flow and you should NOT catch it.<br>class Example {<br>int x;<br>Example(this.x) : assert(x != 0);<br>}<br>In debug mode, if x is 0 an AssertionError is thrown. You shouldn’t catch it and that’s<br>perfectly fine because you, the developer, must see that kind of error: it signals you’ve<br>coded something in the wrong way. The IDE will produce an alert when an object of type<br>Error is being caught.<br> In practice you’re allowed to catch Errors but you shouldn’t. This kind of<br>exceptions signal that you, the programmer, failed something and you must see<br>it because a fix is required!<br>Error is an alert for the developer telling him that something really bad happened, such<br>as an index gone out of the bounds or a critical I/O issue.<br>The usage difference lies on the logical concept.<br>• You almost always want to throw an object that implements Exception because you are<br>the owner of the code and you decide what’s wrong. Anyone else going to use your code<br>will catch your exception object in order to know that something went wrong.<br>• You want to extend (and not implement) Error if you’re dealing with particular code that<br>might cause I/O issues, lists out of bounds or other “particular” error that a programmer<br>can do.<br>Put in other terms, exceptions are “logical errors” that can be fixed while errors are “language<br>specific” mistakes that cause core problems in your code. Other recommendations taken from<br>2</p><p><a href="https://api.dart.dev/stable/2.7.0/dart-core/Exception-class.html">https://api.dart.dev/stable/2.7.0/dart-core/Exception-class.html</a></p><p>Flutter Complete Reference</p><p>133</p><p>Chapter 5. Inheritance and Exceptions<br>the official guidelines</p><p>3</p><p>are:</p><p>1. In a try block you should use on to catch specific types and decide what to do according<br>with the related error.<br>try {<br>// code…<br>} catch (e) {<br>// handle…<br>}<br>This code is really bad because it catches everything, including Error (or its subtypes)<br>which should not be caught. What you’ve just seen is the “Pokémon exception handling”<br>and it’s not a joke! Even the official Dart doc mentions it.<br> It actually makes sense: the Pokémon motto is “Gotta catch ’em all” because<br>the goal of the game is capturing any Pokémon encountered during the journey.<br>You don’t want to be a Pokémon programmer who bravely catches any exception<br>with no regards, don’t you?<br>If you really need to “eat” as many exceptions as possible, use this version:<br>try {<br>// code…<br>} on Exception catch (e) {<br>// handle…<br>}<br>It’s still not good but at least way better than before because Error is not captured and<br>it’s still free to propagate.<br>2. Use on SomeException catch (e) to implement a logic for any type of thrown object.<br>3. Don’t “eat” exceptions. If you really need to do nothing when an exception occurs, print a<br>message to the console or show a popup to notify your users that something’s gone wrong.<br>try {<br>// Exception is ‘eaten’ because when caught, nothing happens<br>} on Exception catch (e) {}<br>3</p><p><a href="https://dart.dev/guides/language/effective-dart/usage#error-handling">https://dart.dev/guides/language/effective-dart/usage#error-handling</a></p><p>Flutter Complete Reference</p><p>134</p><p>Chapter 5. Inheritance and Exceptions<br>4. If you implement Exception, append it at the end of your custom class name such as<br>FractionException or NumeratorNullException. The same concept applies when you<br>deal with Error.<br>5. Do not catch exceptions objects whose type is Error.<br>6. If you want to rethrow an exception, you should use rethrow rather than throwing the<br>same object again with throw 4 .<br>try {<br>try {<br>throw FormatException();<br>} on Exception catch (e) {<br>print(“$e”);<br>rethrow;<br>}<br>} catch (e2) {<br>print(“$e2”);<br>}</p><p>try {<br>try {<br>throw FormatException();<br>} on Exception catch (e) {<br>print(“$e”);<br>throw e;<br>}<br>} catch (e2) {<br>print(“$e2”);<br>}</p><p>.<br>Both ways of rethrowing an exception are valid but you should prefer the usage of rethrow<br>(on the left) because is preserves the original stack trace of the exception. throw instead<br>resets the stack trace to the last thrown position.</p><p>4</p><p><a href="https://dart.dev/guides/language/effective-dart/usage#do-use-rethrow-to-rethrow-a-caught-exception">https://dart.dev/guides/language/effective-dart/usage#do-use-rethrow-to-rethrow-a-caught-exception</a></p><p>Flutter Complete Reference</p><p>135</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9c6beece3e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Complete Reference: Chapter 4]]></title>
            <link>https://medium.com/@linsaw49/flutter-complete-reference-chapter-4-69ee7d5a78bd?source=rss-a3278f83f046------2</link>
            <guid isPermaLink="false">https://medium.com/p/69ee7d5a78bd</guid>
            <dc:creator><![CDATA[saw lin]]></dc:creator>
            <pubDate>Tue, 02 Aug 2022 17:05:03 GMT</pubDate>
            <atom:updated>2022-08-02T17:05:03.990Z</atom:updated>
            <content:encoded><![CDATA[<p>4 | Classes<br>Up to now you’ve seen us saying many times the claim that Dart is an OOP language and now<br>we’re finally going to prove it. There are a lot of similarities with the most popular programming<br>language so you probably are already familiar with the concepts.<br>class Person {<br>// Instance variables<br>String name;<br>String surname;</p><p>}</p><p>// Constructor<br>Person(String name, String surname) {<br>this.name = name;<br>this.surname = surname;<br>}</p><p>This syntax is almost identical to Java, C# or C++ and that’s very good: if you’re going to<br>learn the language, there’s nothing you’ve never seen before. Some keywords might be different<br>but the essence is always the same.<br> Every object is an instance of a class. Dart classes, even if it’s not explicitly<br>written in the declaration, descend from Object and in the next chapter you will see<br>the benefits. In Delphi and C# as well, any class implicitly derives from Object.<br>In any class you have methods (it’s the OOP way to call functions) which can be public or<br>private. The keyword this refers to the current instance of the class. Dart has NO method<br>overload so you cannot have more than a function with the same name. For this reason, you’ll<br>Flutter Complete Reference</p><p>74</p><p>Chapter 4. Classes<br>see how named constructors come to the help.<br>class Example {<br>// Doesn’t compile; you have to use different names<br>void test(int a) {}<br>void test(double x, double y) {}<br>}<br>You might be able to write this in other programming languages because methods have the same<br>name but different signature. In Dart it’s not possible, every function name (in the same class)<br>must be unique. Before going into the details of classes, look at the cascade notation.<br>class Test {<br>String val1 = “One”;<br>String val2 = “Two”;</p><p>}</p><p>int randomNumber() {<br>print(“Random!”);<br>return Random().nextInt(10);<br>}</p><p>Given this class, you have two ways to give a value to the variables:<br>// first way, the “classic” one<br>test.val1 = “one”;<br>test.val2 = “two”;<br>// second way, using the cascade operator<br>test..val1 = “one”<br>..val2 = “two”;<br>It’s just a shorthand version you can use when there are multiple values of the same objects that<br>has to be initialized. You can do the same even with methods but the returned value, if any, will<br>be ignored. For this reason, the cascade notation is useful when calling a series of void methods<br>on the same object.<br>Test()..randomNumber()<br>..randomNumber()<br>..randomNumber();<br>Here the integer returned by randomNumber() is discarded but the body is executed. If you<br>Flutter Complete Reference</p><p>75</p><p>Chapter 4. Classes<br>run the snipped, you’ll get Random! printed three times in the console. In case of nullable<br>values…<br>MyClass? test = MyClass();<br>test?..one()<br>..two()<br>..three();<br>… the cascade notation has to start with ?.. in order to be null-checked before dereferencing.<br>In Dart there cannot be nested classes.</p><p>4.1</p><p>Libraries and visibility</p><p>In the Dart world, when you talk about a “library” you’re referring to the code inside a file with<br>the .dart extension. If you want to use that particular library, you have to reference its content<br>with the import keyword.<br> If you aren’t sure you’ve understood the above statement, here’s an example.<br>Let’s say there’s the need to handle fractions in the form numerator / denominator :<br>you are going to create a file named fraction.dart.<br>// === Contents of fraction.dart ===<br>class MyFraction {<br>final int numerator;<br>final int denominator;</p><p>}</p><p>//… other code</p><p>Congratulations, you have just created the fraction library! It can be used by any<br>other .dart file that references it via import.<br>import ‘package:fraction.dart’;<br>void main() {<br>// You could have written ‘new Fraction(1, 2)’ but<br>// starting from Dart 2.0 ‘new’ is optional<br>final frac = Fraction(1, 2);<br>Flutter Complete Reference</p><p>76</p><p>Chapter 4. Classes<br>}<br>You can also use the library keyword to “name” your library as you prefer. This<br>keyword really just names the library as you like, nothing more, and it’s not required.<br>library super_duper_fraction;<br>class MyFraction {<br>final int numerator;<br>final int denominator;<br>const MyFraction(this.numerator, this.denominator);<br>}<br>.<br>The import directive accepts a string which must contain a particular scheme. For built-in<br>libraries you have to use the dart: prefix followed by the library name:<br>import ‘dart:math’;<br>import ‘dart:io’;<br>import ‘dart:html’;<br>Everything else that doesn’t belong to the Dart SDK, such as a custom library created by you<br>or another developer in the community, must be prefixed by package.<br>import ‘package:fraction.dart’;<br>import ‘package:path/to/file/library.dart’;<br>It could happen that two different libraries have implemented a class with the same name; the<br>only possible technique to avoid ambiguity is called “library aliases”. It’s a way to reference the<br>contents of a library under a different name.<br>// Contains a class called ‘MyClass’<br>import ‘package:libraryOne.dart’;<br>// Also contains a class called ‘MyClass’<br>import ‘package:libraryTwo.dart’ as second;<br>void main() {<br>// Uses MyClass from libraryOne<br>var one = MyClass();<br>//Uses MyClass from libraryTwo.<br>Flutter Complete Reference</p><p>77</p><p>Chapter 4. Classes</p><p>}</p><p>var two = second.MyClass();</p><p>You can selectively import or exclude types using the show and hide keywords:<br>• import ‘package:libraryOne.dart’ show MyClass; Imports only MyClass and discards<br>all the rest.<br>• import ‘package:libraryTwo.dart’ hide MyClass; Imports everything except MyClass.<br>At the moment, you have the basics of libraries (simple creation and usage). In chapter 23<br>you’ll learn how to create a package (a collection of libraries and tools) and how to publish it at<br><a href="https://pub.dev/">https://pub.dev</a>.</p><p>4.1.1</p><p>Encapsulation</p><p>You may be used to hide implementation details in your classes using public, protected and private<br>keywords but there’s no equivalent in Dart. Every member is public by default unless you append<br>an underscore (_) which makes it private to its library. If you had this file…<br>// === File: test.dart ===<br>class Test {<br>String nickname = “”;<br>String _realName = “”;<br>}<br>… you could later import the library anywhere:<br>// === File: main.dart ===<br>import ‘package:test.dart’;<br>void main() {<br>final obj = Test();</p><p>}</p><p>// OK<br>var name = obj.nickname;<br>// ERROR, doesn’t compile<br>var real = obj._realName;</p><p>The variable nickname is public and everyone can see it but _realName can be seen ONLY<br>inside test.dart. In other words, if you put the underscore in front of the name of a variable, it<br>Flutter Complete Reference</p><p>78</p><p>Chapter 4. Classes<br>is visible only within that file.<br>// === File: main.dart ===<br>class Test {<br>String nickname = “”;<br>String _realName = “”;<br>}<br>void main() {<br>final obj = Test();</p><p>}</p><p>// Ok<br>var name = obj.name;<br>// Ok, it works because ‘Test’ is in the same file<br>var real = obj._realName;</p><p>We’ve moved everything in the same file: now both Test and main() belong to the same library<br>and so _realName is not private anymore.</p><p> The same rules on package private members also apply to classes and functions.<br>For example, void something() is visible from the outside while void _something()<br>is private to its library.<br>// Inside a file called users.dart<br>class Users { }<br>class _UsersHelper { }<br>In this case, Users is visible while _UsersHelper is package-private (exactly as it<br>happens with variables and methods).<br>In Dart everything is “public” by default; if you append an underscore at the front, it becomes<br>“private”. There is no way to define “protected” members or variables (where protected is a<br>typical OOP keyword that makes a member or variable accessible only by subclasses of a certain<br>type.).<br>Flutter Complete Reference</p><p>79</p><p>Chapter 4. Classes</p><p>4.1.2</p><p>Good practices</p><p>We strongly recommend to NOT put everything in a single file (or a few ones) for the following<br>reasons:<br>• Dealing with thousands of lines of code containing literally everything is not good at all.<br>Maintenance is going to be hard and you’re on the good way to become a professional<br>“spaghetti code” writer!<br>• If you placed everything in the same file, you’d expose private details of the class. We’ve<br>seen that private members exist only if classes are put in separated libraries (files).<br>Try to have one file per class or at maximum a few classes that are closely related (they should<br>have the same purpose). When you write a Dart program, in general you have this folder<br>structure:<br>root<br>| — lib<br>|<br>| — main.dart<br>|<br>| — routes<br>|<br>| — other_folders<br>| — tests<br>| — tools<br>You’ll learn throughout the chapters how to create a robust folder hierarchy. The minimal<br>Dart/Flutter project is made up of a lib/ folder and a main.dart entry point file.</p><p>4.2</p><p>Constructors</p><p>The constructor is a special function with the same name of the class and doesn’t carry a return<br>type. To invoke it, the syntax is the most common one you can imagine:<br>final myObject = new MyClass();<br>Starting from Dart 2, the keyword new can be omitted. It’s something you’re always going to do,<br>especially while writing Flutter apps.<br>final myObject = MyClass();<br>As example, in this chapter we are creating a library to work with fractions and rational numbers. To get started, there’s the need to create a file called fraction.dart with the following<br>contents:<br>Flutter Complete Reference</p><p>80</p><p>Chapter 4. Classes<br>class Fraction {<br>int? _numerator;<br>int? _denominator;</p><p>}</p><p>Fraction(int numerator, int denominator) {<br>_numerator = numerator;<br>_denominator = denominator;<br>}</p><p>In this case variables must be nullables because they are initialized, by default, to null. The<br>body of the constructor is called after the variables initialization. If you want to get rid of<br>nullables there are two options:<br>1. Declare variables as late final to tell the compiler to not emit an error. They are going<br>to be initialized later but anyway before being accessed for the first time ever.<br>class Fraction {<br>late final int _numerator;<br>late final int _denominator;</p><p>}</p><p>Fraction(int numerator, int denominator) {<br>_numerator = numerator;<br>_denominator = denominator;<br>}</p><p>Because of the final modifier, variables cannot be changed anymore after their initialization. You could have only used late but variables would be mutable then:<br>class Fraction {<br>late int _numerator;<br>late int _denominator;</p><p>}</p><p>Fraction(int numerator, int denominator) {<br>_numerator = numerator;<br>_denominator = denominator;<br>}</p><p>In both cases, members are NOT initialized immediately because the body of the construcFlutter Complete Reference</p><p>81</p><p>Chapter 4. Classes<br>tor is executed after the variable initialization phase.<br>2. The Dart team recommends going for the “initializing formal”<br>readable and it initializes the variables immediately.</p><p>1</p><p>approach as it’s more</p><p>class Fraction {<br>int _numerator;<br>int _denominator;</p><p>}</p><p>Fraction(this._numerator, this._denominator);</p><p>It’s just syntactic sugar to immediately assign values to members. In this case, variables<br>initialization is executed first so no need to use nullable types or late. This kind of<br>initialization happens before the execution of the constructor’s body.<br>Keep in mind that constructor bodies are executed after the variable initialization phase. The<br>second approach is very common and you should get used to it, even if your class only declares<br>final fields.<br>class Fraction {<br>final int _numerator;<br>final int _denominator;</p><p>}</p><p>Fraction(this._numerator, this._denominator);</p><p>If your class doesn’t define a constructor, the compiler automatically adds a default constructor<br>with no parameters and an empty body. With the “initializing formal” you can still declare a<br>body to perform additional setup for the class.<br>class Fraction {<br>final int _numerator;<br>final int _denominator;<br>late final double _rational;<br>Fraction(this._numerator, this._denominator) {<br>_rational = _numerator / _denominator;<br>doSomethingElse();<br>1</p><p><a href="https://dart.dev/guides/language/effective-dart/usage#do-use-initializing-formals-when-possible">https://dart.dev/guides/language/effective-dart/usage#do-use-initializing-formals-when-possible</a></p><p>Flutter Complete Reference</p><p>82</p><p>Chapter 4. Classes</p><p>};</p><p>}</p><p>You could only write Fraction(this._numerator) to initialize exclusively _numerator but then<br>_denominator would be set to null by the compiler. Keep in mind that you cannot have named<br>optional parameters starting with an underscore.<br>// Doesn’t compile<br>Fraction({this._numerator, this._denominator});<br>However, you can have positional parameters starting with an underscore:<br>// Ok but pay attention to non-nullability<br>Fraction([this._numerator, this._denominator]);</p><p>4.2.1</p><p>Initializer list</p><p>When using the initializing formal approach, the names of the variables must match the ones<br>declared in the constructor. This could lead to an undesired exposure of some internals of the<br>class:<br>class Test {<br>int _secret;<br>double _superSecret;</p><p>}</p><p>Test(this._secret, this._superSecret);</p><p>What if you wanted to keep int _secret (private) but with a different name in the constructor?<br>Use an initializer list! It’s executed before the body and thus variables are immediately initialized.<br>No need for nullable types or late.<br>class Test {<br>int _secret;<br>double _superSecret;</p><p>}</p><p>Test(int age, double wallet)<br>: _secret = age,<br>_superSecret = wallet;</p><p>In this way the constructor is asking you for age and wallet but the user has no idea that<br>Flutter Complete Reference</p><p>83</p><p>Chapter 4. Classes<br>internally they’re treated as _secret and _superSecret. It’s basically a way to “rename” internal<br>private properties you don’t want to expose.</p><p>4.2.2</p><p>Named constructors</p><p>Named constructors are generally used to implement a default behavior the user expects from<br>your class. They are the only alternative to have multiple constructors since Dart has no method<br>overload.<br>class Fraction {<br>int _numerator;<br>int _denominator;<br>Fraction(this._numerator, this._denominator);</p><p>}</p><p>// denominator cannot be 0 because 0/0 is not defined!<br>Fraction.zero() :<br>_numerator = 0,<br>_denominator = 1;</p><p>At this point you can use the named constructor in your code like if it were a static method<br>call.<br>void main() {<br>// “Traditional” initialization<br>final fraction1 = Fraction(0, 1);</p><p>}</p><p>// Same thing but with a named constructor<br>final fraction2 = Fraction.zero();</p><p>In general constructors aren’t inherited by a subclass so, if they are needed across the hierarchy,<br>every subclass must implement its own named constructor. If we had written a named constructor<br>with a body…<br>class Fraction {<br>int? _numerator;<br>int? _denominator;<br>Flutter Complete Reference</p><p>84</p><p>Chapter 4. Classes</p><p>}</p><p>Fraction.zero() {<br>_numerator = 0;<br>_denominator = 1<br>}</p><p>… we would have had to use nullable instance variables as constructors’ bodies are always<br>executed after variables’ initialization.</p><p>4.2.3</p><p>Redirecting constructors</p><p>Sometimes you might have a constructor that does almost the same thing already implemented<br>by another one. It may be the case to use redirecting constructors in order to avoid code duplication:<br>Fraction(this._numerator, this._denominator);<br>// Represents ‘1/2’<br>Fraction.oneHalf() : this(1, 2);<br>// Represents integers, like ‘3’ which is ‘3/1’<br>Fraction.whole(int val) : this(val, 1);<br>Where Fraction.oneHalf() is just another way to call Fraction(1, 2) but you’ve avoided code<br>repetition. This feature is very powerful when mixed with named constructors.</p><p>4.2.4</p><p>Factory constructors</p><p>The factory keyword returns an instance of the given class that’s not necessarily a new one. It<br>can be useful when:<br>• You want to return an instance of a subclass instead of the class itself,<br>• You want to implement a singleton (the Singleton pattern),<br>• You want to return an instance from a cache.<br>Factory constructors are like static methods and so they don’t have access to this. There cannot<br>be together a factory and a “normal” constructor with the same name.<br>class Test {<br>static final _objects = List&lt;BigObject&gt;();<br>factory Test(BigObject obj) {<br>Flutter Complete Reference</p><p>85</p><p>Chapter 4. Classes<br>if (!objects.contains(obj))<br>objects.add(obj);</p><p>}</p><p>}</p><p>return Test._default();</p><p>// This is a private named constructor and thus it can’t be called<br>// from the outside<br>Test._default() {<br>//do something…<br>}</p><p>In the example, since BigObject requires a lot of memory and the list is very very long, we’ve<br>declared objects as static. This technique is often used to save memory and reuse the same<br>object across multiple objects of the same type.<br> If the list weren’t static (just a normal instance variable), it would be created<br>every time that a Test object is instantiated. It’d be a waste of memory and a performance problem; in this way we’re guaranteed that there’s an unique list created<br>only once.<br>In this case the factory constructor is essential because it takes care of updating the _objects<br>cache. Factories are called “normally” like if they were a regular constructor:<br>// Calls the factory constructor<br>final a = Test();</p><p>4.2.5</p><p>Instance variables initialization</p><p>As we’ve already seen, “normal” non-nullable variables have to be initialized either via initializing<br>formal or initializer list. In any other case, they’re set to null because constructor bodies run<br>after the instance initialization phase.<br>// Initializing formal<br>class Example {<br>int _a; // Ok — ‘a’ initialized by the constructor<br>Example(this._a);<br>Flutter Complete Reference</p><p>86</p><p>Chapter 4. Classes<br>}<br>class Example {<br>int _a; // Error — ‘a’ not initialized<br>Example(int a) {<br>_a = a;<br>}<br>}<br>If variables aren’t initialized immediately and you want them to be non-nullanle, you can use the<br>late modifier. It works like a “lazy initialization” because with this keyword you allow a nonnullable to be initialized later (but anyway before it gets accessed for the first time ever).<br>// For Dart 2.10 and earlier versions, ‘late’ does not exist so just<br>// remove it. Not initialized variables will be set to ‘null’ by default.<br>class Example {<br>late int a;</p><p>}</p><p>void printExample() {<br>a = 5;<br>print(“$a”);<br>a = 2;<br>print(“$a”);<br>}</p><p>If you tried to use the variable before it gets assigned for the first time, you would get a compilation<br>error. Always be sure to have the initialization done before using it.<br>class Example {<br>late int a;</p><p>}</p><p>void printExample() {<br>// Compilation error<br>print(“$a”);<br>a = 5;<br>}</p><p>Using a like above causes an error because it’s accessed before being initialized. There’s also the<br>Flutter Complete Reference</p><p>87</p><p>Chapter 4. Classes<br>possibility to declare a late final variable which behaves in the same way but with the only<br>exception that it can be assigned only once.<br>class Example {<br>late final int a;</p><p>}</p><p>void printExample() {<br>a = 5;<br>print(“$a”);<br>//a = 6; ← This would be an error<br>}</p><p>Once a is set with a = 5; you can’t re-assign it anymore because of the final modifier. Instead,<br>if it were a simple late int a;, you could have re-assigned it multiple times.<br>late final double a = takesLongTime();<br>Thanks to the usage of the late final combination you can lazily initialize a variable that is<br>going to hold a value computed from a function. You can assign it immediately or, as we’ve<br>just seen, in a second moment. The function takesLongTime() will only be called once a is<br>accessed.</p><p>4.2.6</p><p>Good practices</p><p>Following what the official documentation<br>writing constructors for your classes:</p><p>2</p><p>suggests, here’s some tips you should consider while</p><p>1. Prefer using the “initializing formal” approach rather than initializing variables directly in<br>the body of the constructor. Doing so, you’ll avoid the usage of nullable types or late.<br>2. When you use the initializing formal, the types of the variables are deduced automatically<br>to reduce the verbosity. Omit the types because they’re useless.<br>// Ok but useless<br>Constructor(String this.a, double this.b) {}<br>// OK<br>Constructor(this.a, this.b);<br>3. When you have an empty constructor with no body, use the semicolon instead of the empty<br>brackets.<br>2</p><p><a href="https://dart.dev/guides/language/effective-dart/usage#constructors">https://dart.dev/guides/language/effective-dart/usage#constructors</a></p><p>Flutter Complete Reference</p><p>88</p><p>Chapter 4. Classes<br>// Bad<br>Constructor(this.a, this.b) {}<br>// Good<br>Constructor(this.a, this.b);<br>4. Do not use the new keyword when creating new instances of objects. In modern Dart and<br>Flutter code, new never appears.<br>5. We recommend using redirecting constructors to avoid code duplication. It makes maintenance easier.<br>6. Try to not use the late keyword because it could lead to hard maintenance (you’d have<br>to manually keep an eye on the initialization of variables). Whenever possible, initialize<br>variables as soon as they are declared.<br>7. In the second part of the book we’ll show a case where late or late final are required.<br>They’ll be used to initialize values inside the state of a Widget.<br>class Example extends State {<br>late int value;</p><p>}</p><p><a href="http://twitter.com/override">@override</a><br>void initState() {<br>super.initState();<br>value = 0;<br>}</p><p>In short, subclasses of State cannot define a constructor and you have to perform the<br>initialization of the variables in the initState() method. In order do to this, late is<br>essential.<br>The syntax for private constructors in Dart might seem a bit weird at first. Generally, a private<br>constructor is used in conjunction with a factory that returns a subtype or an instance of the<br>actual object with certain criteria.<br>class Example {<br>final a;<br>// Private constructor<br>Example._(this.a);<br>factory Example(int value) {<br>Flutter Complete Reference</p><p>89</p><p>Chapter 4. Classes</p><p>}</p><p>}</p><p>final c = value * 3;<br>return Example._(c);</p><p>A private constructor is declared using the ._() notation. In the example, the class can still be<br>instantiated but only because we’ve defined a factory. In this case…<br>final ex = Example(10);<br>… we’re not calling the “normal” constructor (because it’s package private) but instead the<br>factory one.</p><p>4.3</p><p>const keyword</p><p>The const keyword can be used when you have to deal with compile-time constant values such<br>as strings or numbers. It can automatically deduce the type.<br>// type of ‘number’ is int<br>const number = 5<br>// explicitly write the type<br>const String name = ‘Alberto’;<br>const sum = 5.6 + 7.34;<br>It’s true that final and const are very similar at first glance and they also share the same syntax<br>style. A very intuitive way to determine which one you can choose is ask yourself: is this value<br>already well defined? is it known at compile time? Let’s find out why.<br>• final. Use it when the value is not known at compile time because it will be evaluated/obtained at runtime. Common usages are I/O from the disk or HTTP requests. For<br>example, this is how you read a text file from the disk (more on this in A.1):<br>final contents = File(‘myFile.txt’).readAsString();<br>// const contents = File(‘myFile.txt’).readAsString();<br>// ^ does not compile!<br>The compiler doesn’t know in advance which is the content of myFile.txt because it will<br>be read only when the program will be running (so after the compilation). For this reason,<br>you can only use final.<br>Flutter Complete Reference</p><p>90</p><p>Chapter 4. Classes<br>• const. Use it when the value is computed at compile time, for example with integers,<br>doubles, Strings or classes with a constant constructor (more on it in the next section).<br>const a = 1;<br>// final a = 1 -&gt; it works as well<br>If it works with const, it works also with final because anything that is const is also<br>final.<br>Instance variables can only be declared as final while const can be applied in combination with<br>the static keyword.<br>class Example {<br>// OK<br>final double a = 0.0;<br>// NO, instance variables can only be ‘final’<br>const double b = 0.0;</p><p>}</p><p>// OK<br>static const double PI = 3.14;<br>// OK but without type annotation<br>static const PI = 3.14;</p><p>The real power of const comes when combined with constructors and, in Flutter, it can lead to<br>an important performance boost.<br> Variables and methods marked with the static modifier are available on the class<br>itself and not on instances. In practice it means that you can use them without having<br>to create an object.<br>class Example {<br>static const name = “Flutter”;<br>static String test() =&gt; “Hello, I am $name!”;<br>}<br>void main() {<br>final name = Example.name;<br>final text = Example.test();<br>}<br>Flutter Complete Reference</p><p>91</p><p>Chapter 4. Classes<br>Both variables are strings and they’ve been retrieved without creating an instance of<br>Example; static members belong to the “class scope” and you cannot use this.<br>class Example {<br>int a = 0;<br>static void test() {<br>// Doesn’t compile<br>final version = this.a;<br>print(“$version”);<br>};<br>}<br>Since you don’t have to create objects to call static methods, this cannot work because it refers to the current instance that gets never created.</p><p>4.3.1</p><p>const constructors</p><p>In Dart you can append the const keyword in front of a constructor only if you’re going to<br>initialize a series of final (immutable) variables.<br>// Compiles<br>class Compiles {<br>final int a;<br>final int b;<br>const Compiles(this.a, this.b);<br>}<br>// Does not compile because a is mutable (not final)<br>class DoesNot {<br>int a;<br>final int b;<br>const DoesNot(this.a, this.b);<br>}<br>If your class only has final variables it’s said to be an “immutable class” and you should really<br>instantiate it with a const constructor. The compiler can perform some optimizations.<br>final example1 = const Compiles(); // (1) constant object<br>final example2 = Compiles();<br>// (2) not a constant object!<br>Flutter Complete Reference</p><p>92</p><p>Chapter 4. Classes<br>In example (1) we’re calling the constant constructor but in (2) we’re not. Even if your class<br>only has constant constructors, objects can be instantiated as constants only with the const<br>keyword. When put in front of a collection, such as a list, everything inside that container will<br>automatically be const (if it is allowed to be constant).<br>class Test {<br>// constant constructor<br>const Test();<br>}<br>const List&lt;Test&gt; listConst = [Test(), Test()]; // (1)<br>final List&lt;Test&gt; listConst2 = [Test(), Test()]; // (2)<br>In (1) everything inside the list is automatically “converted” into a const value while in (2) it<br>doesn’t happen, meaning that the contents of listConst2 aren’t constant. The final keyword<br>in front of a list just makes it impossible to change the reference assigned to listConst2 but<br>does NOT call the constant constructor (while example (1) does).<br>// Bad<br>const List&lt;Test&gt; list1 = [const Test(), const Test()]; // (1)<br>// Good<br>const List&lt;Test&gt; list2 = [Test(), Test()]; // (2)<br>You should avoid version (1) because calling const Test() is not necessary. Any constant<br>collection initializes its children calling their const constructor (if any, otherwise a compilation<br>error occurs).</p><p>4.3.2</p><p>Good practices and annotations</p><p>If you know that variables in your class will never change, you really should make them final<br>and use a const constructor. As we’ve already said, constant constructors play a very important<br>role in Flutter because they allow “caching” on instances.<br> Don’t get “obsessed” by immutable classes and const constructors because you<br>simply can’t use them in every situation. If your instance variables cannot be final<br>that’s perfectly fine; the environment and the compiler are very powerful and your<br>final product won’t suffer of speed degradations due to the lack of immutability.<br>Any class with a constant constructor can be used as annotation: they’re are generally put<br>Flutter Complete Reference</p><p>93</p><p>Chapter 4. Classes<br>before the name of a class or method. An annotation is preceded by the “at” sign (@). In the<br>next section, we will see that overriding methods is usually done in the following way:<br>class MySubclass extends SuperClass {<br><a href="http://twitter.com/override">@override</a><br>void defineMethod() {}<br>}<br>The <a href="http://twitter.com/override">@override</a> annotation does nothing in practice: it just tells the developer that defineMethod<br>has been overridden. If you looked at how the override annotation is declared in the Dart SDK,<br>you’ll find simply the following:<br>// This class has a constant constructor and so it can be used as annotation<br>class _Override {<br>const _Override();<br>}<br>// the actual “<a href="http://twitter.com/override">@override</a>” annotation<br>const Object override = _Override();<br>The class has been made private (_Override) because its instantiation is useless as it does<br>nothing. However, thanks to the const Object override variable being public, there’s an<br>“alias” of the _Override class which can be used as annotation. They’re generally used for:<br>• reminding the developer about something, such as in the case of <a href="http://twitter.com/override">@override</a>;<br>• before Dart 2.10, the <a href="http://twitter.com/required">@required</a> annotation was used by the IDE to bring the developer’s<br>attention to the fact that a named optional parameter is required;<br>• some packages, such as json_serializable we’re going to cover in chapter 15, rely on annotations to add additional information about a class, a method or a member. Annotations<br>can be used to pass data to code generation tools.<br>Annotations can also have parameters but in this case you aren’t doing the above “trick” of<br>declaring a global variable exposing a private class. Just create a normal class, with a const<br>constructor and use it as follows:<br>// Use this as annotation but it takes a param<br>class Something {<br>final int value;<br>const Something(this.value);<br>}<br>Flutter Complete Reference</p><p>94</p><p>Chapter 4. Classes</p><p><a href="http://twitter.com/Something">@Something</a>(10)<br>class Test {}</p><p>4.4</p><p>Getters and setters</p><p>When a public variable is declared, anyone can freely manipulate it but it may not a good idea<br>because the class partially loses control of its members. If we had written this…<br>class Fraction {<br>int numerator;<br>int denominator;<br>Fraction(this.numerator, this.denominator);<br>}<br>… at a certain point someone could have changed the numerator and the denominator without<br>any control introducing unexpected behaviors due to a wrong internal state.<br>void main() {<br>final frac = Fraction(1, 7);</p><p>}</p><p>frac.numerator = 0;<br>frac.denominator = 0;</p><p>Having set both numerator and denominator to 0 there will be problems at runtime due to an<br>invalid division operation. We can fix this problem using a getter , which makes the variables<br>read-only.<br>class Fraction {<br>int _numerator;<br>int _denominator;<br>Fraction(this._numerator, this._denominator);</p><p>}</p><p>// Getters are read-only<br>int get numerator =&gt; _numerator;<br>int get denominator {<br>return _denominator;<br>}</p><p>Flutter Complete Reference</p><p>95</p><p>Chapter 4. Classes<br>The getter numerator returns an int, _numerator; the getter denominator does the same thing<br>with an equivalent syntax. Like it happens with methods, when there is an one-liner expression<br>or value to return, the =&gt; (arrow) syntax can be used.<br>void main() {<br>final frac = Fraction(1, 7);</p><p>}</p><p>// Compilation error, numerator is read-only<br>frac.numerator = 0;<br>// No problems here, we can read its value<br>final num = frac.numerator;</p><p>The code is now safe because we can expose both numerator and denominator but it’s guaranteed<br>that they cannot be freely modified. Internally, _numerator and _denominator are “safe” because<br>they aren’t visible from the outside. Just as example, we’re going to see how to write a setter<br>for the denominator. So far it’s read-only but with a setter it becomes editable:<br>class Fraction {<br>int _numerator;<br>int _denominator;<br>Fraction(this._numerator, this._denominator);<br>// getters<br>int get numerator =&gt; _numerator;<br>int get denominator =&gt; _denominator;</p><p>}</p><p>// setter<br>set denominator(int value) {<br>if (value == 0) {<br>// Or better, throw an exception…<br>_denominator = 1;<br>} else {<br>_denominator = value;<br>}<br>}</p><p>There can be the same name for a setter and a getter so that a property can be read/written using<br>the same identifier. Setters should be used to make “safe edits” on variables; they often contain a<br>Flutter Complete Reference</p><p>96</p><p>Chapter 4. Classes<br>validation logic which makes sure that the internal state of the class doesn’t get corrupted.<br>void main() {<br>final frac = Fraction(1, 7);</p><p>}</p><p>var den1 = frac.denominator; // den1 = 7<br>frac.denominator = 0; // the setter changes it to 1<br>den1 = frac.denominator<br>// den1 = 1</p><p>To sum it up, getters and setters are used to control the reading/writing on variables. They are<br>methods under the hood but with a “special” syntax that uses the get and set keywords.</p><p>4.4.1</p><p>Good practices</p><p>Our recommendation is to keep the body of getters and setters as short as possible in benefit of<br>code readability. You shouldn’t put any loop that might slow down the assignment/retrieval of<br>a value. The official documentation 3 also has something to say:<br>• When a variable has to be both public and read-only, just mark it as final without associating a getter to it.<br>// Bad<br>class Example {<br>final _address = “<a href="https://fluttercompletereference.com/">https://fluttercompletereference.com</a>&quot;;<br>String get address =&gt; _address;<br>}<br>// Good<br>class Example {<br>final address = “<a href="https://fluttercompletereference.com/">https://fluttercompletereference.com</a>&quot;;<br>}<br>If it’s final, it’s already a read-only variable because nothing can change its content. In<br>this case a getter is simply useless.<br>• Avoid wrapping public variables with getters and setters if there’s no validation logic.<br>class Example {<br>var _address = “<a href="https://fluttercompletereference.com/">https://fluttercompletereference.com</a>&quot;;<br>3</p><p><a href="https://dart.dev/guides/language/language-tour#getters-and-setters">https://dart.dev/guides/language/language-tour#getters-and-setters</a></p><p>Flutter Complete Reference</p><p>97</p><p>Chapter 4. Classes</p><p>}</p><p>String get address =&gt; _address;<br>set address(String value) =&gt; _address = value;</p><p>It compiles but there’s no point in doing that: both getter and setter don’t perform any<br>particular logic as they just serve the variable as it is. Prefer doing this:<br>class Example {<br>var address = “<a href="https://fluttercompletereference.com/">https://fluttercompletereference.com</a>&quot;;<br>}<br>In general, use getters when you want to expose a variable but in “read-only mode” and setters<br>when you want to filter/check the value that is going to be assigned.</p><p>4.5</p><p>Operators overload</p><p>When you deal with primitive types you use operators very often: 5 + 8 is a sum between two<br>int types happening with the + operator. We are going to do the same with Fraction class.<br>class Fraction {<br>Fraction operator+(Fraction other) =&gt;<br>Fraction(<br>_numerator * other._denominator +<br>_denominator * other._numerator,<br>_denominator * other._denominator<br>);<br>Fraction operator-(Fraction other) =&gt; …<br>Fraction operator*(Fraction other) =&gt; …</p><p>}</p><p>Fraction operator/(Fraction other) =&gt; …</p><p>Operator overloading gives the possibility to customize the usage of operators in your classes.<br>We have overloaded the + operator so that we can easily sum two fractions instead of having to<br>create an add(Fraction value) method, like it happens with Java.<br>void main() {<br>Flutter Complete Reference</p><p>98</p><p>Chapter 4. Classes<br>// 2/5<br>final frac1 = Fraction(2, 5);<br>// 1/3<br>final frac2 = Fraction(1, 3);</p><p>}</p><p>// 2/5 + 1/3 = 11/15<br>final sum = frac1 + frac2</p><p>They work like normal methods with the only exception that the name must be in the form<br>operator{sign} where sign is a supported Dart operator:<br>• Arithmetic operators like +, -, *, or /.<br>• Relational operators such as &gt;=, &lt;=, &gt; or &lt;.<br>• Equality operators like != and ==<br>And many more. There are no restrictions on the types you can handle with the operators,<br>meaning that we could also sum fractions with integers: operator+(int other). You cannot<br>overload the same operator more than once in the same class.</p><p>4.5.1</p><p>callable classes</p><p>There is a special call() method which is very closely related to an operator overload because<br>it allows classes to be called like if they were functions with the () operator.<br> You can give call() as many parameters as you want as there are no restrictions<br>on their types. The function can return something or it can simply be void.<br>Let’s give a look at this example.<br>class Example {<br>double call(double a, double b) =&gt; a + b;<br>}<br>void main() {<br>final ex = Example();<br>// 1.<br>final value = ex(1.3, -2.2); // 2.<br>Flutter Complete Reference</p><p>99</p><p>Chapter 4. Classes</p><p>}</p><p>print(“$value”);</p><p>1. Classic creation of an instance of the class<br>2. The object ex can act like if it were a function. The call() method allows an object to be<br>treated like a function.<br>Any class that implements call() is said to be a callable class. In Dart, everything is an object<br>and you’ve seen in 3.6.1 that even functions are objects. You can now understand why with the<br>following example:<br>void test(String something) {<br>print(something);<br>}<br>This is a typical void function asking for a single parameter. Actually, the above code can be converted into a callable class that overrides call() returning nothing and asking for a string.<br>// Create this inside ‘my_test.dart’ for example<br>class _Test {<br>const _Test();</p><p>}</p><p>void call(String something) {<br>print(something);<br>}</p><p>const test = _Test();<br>// Somewhere else, for example in main.dart<br>import ‘package:myapp/my_test.dart’;<br>void main() {<br>test(“Hello”);<br>}<br>The function is nothing more than a package private class that overrides call() with a certain<br>signature. Thanks to const test = _Test(); in the last line we’re “hiding” the class and<br>exposing a callable object to be used as function.<br>Flutter Complete Reference</p><p>100</p><p>Chapter 4. Classes</p><p>4.6</p><p>Cloning objects</p><p>Even if it’s not mentioned in the official Dart documentation, there is a standard “pattern” to<br>follow when it comes to cloning objects. Unlike Java, there is no clone() method to override<br>but still you might need to create deep copies of objects:<br>class Person {<br>final String name;<br>final int age;<br>const Person({<br>required this.name,<br>required this.age,<br>});<br>}<br>void main() {<br>const me = const Person(<br>name: “Alberto”,<br>age: 25<br>);<br>const anotherMe = me;<br>}<br>As you already know, the variable anotherMe just holds a reference to me and thus they point<br>to the same object. Changes applied to me will also reflect on anotherMe. If you want to make<br>deep copies in Dart (cloning objects and making them independent), this is the way:<br>class Person {<br>final String name;<br>final int age;<br>const Person({<br>required this.name,<br>required this.age,<br>});<br>Person copyWith({<br>String? name,<br>int? age,<br>}) =&gt; Person(<br>Flutter Complete Reference</p><p>101</p><p>Chapter 4. Classes</p><p>);</p><p>}</p><p>name: name ?? this.name,<br>age: age ?? this.age</p><p><a href="http://twitter.com/override">@override</a><br>String toString() =&gt; “$name, $age”;</p><p>This method is called copyWith() by convention and it takes the same number (and name) of<br>parameters required by the constructor. It creates a new, independent copy of the object (a<br>clone) with the possibility to change some parameters:<br>const me = const Person(<br>name: “Alberto”,<br>age: 25<br>);<br>// Create a deep copy of ‘me’.<br>final anotherMe = me.copyWith();<br>// Create a deep copy of ‘me’ with a different age.<br>final futureMe = const.copyWith(age: 35);<br>print(“$me”);<br>// Alberto, 25<br>print(“$anotherMe”); // Alberto, 25<br>print(“$futureMe”); // Alberto, 35<br>Both anotherMe and futureMe have no side effects on me because the reference is not the same.<br>In fact, copyWith() returns a fresh new instance by copying internal data. Let’s take a look at<br>this line:<br>name: name ?? this.name,<br>Thanks to the ?? operator, if name is null then initialize the clone with value of this.name taken<br>from the instance. In other words, if you don’t pass a custom name to copyWith(), by default a<br>copy of this.name is made. Pay attention to generic containers and objects in general:<br>class Skills {…}<br>class Person {<br>final List&lt;Skills&gt; skills;<br>Flutter Complete Reference</p><p>102</p><p>Chapter 4. Classes<br>const Person({<br>required this.skills<br>});</p><p>}</p><p>Person copyWith({<br>List&lt;Skills&gt;? skills,<br>}) =&gt; Person(<br>skills: skills ?? this.skills<br>);</p><p>This code doesn’t do what you’d expect because List&lt;T&gt;, like any other generic container, is an<br>object and not a primitive type. With the above code you’re just copying references and not<br>making copies. The correct solution is the following:<br>Person(<br>skills: skills ?? this.skills.map((p) =&gt; p.copyWith()).toList();<br>);<br>In this way you’re making a copy of the entire list rather than passing a reference. The above<br>code is just an one-liner way to iterate on each element of the source, making deep copies using<br>copyWith and returning a new list. However, when the list is made up of primitive types, you<br>could use a shortcut:<br>class Person {<br>final List&lt;int&gt; values;<br>const Person({<br>required this.values<br>});</p><p>}</p><p>Person copyWith({<br>List&lt;int&gt;? values,<br>}) =&gt; Person(<br>values: values ?? []..addAll(this.values)<br>);</p><p>Primitive types are automatically copied so instead of using map() (which would be perfectly fine<br>as well) we can use addAll() for a shorter syntax. There is no difference however because it still<br>iterates on every element of the source list. The same example also applies to Map&lt;K, V&gt; and<br>Flutter Complete Reference</p><p>103</p><p>Chapter 4. Classes<br>Set&lt;K&gt;. To sum it up, what you have to keep in mind is:<br>• Deep copies in Dart are made using the copyWith() method. You can give it any other<br>name but you’d better follow the conventions.<br>• When making copies, be sure that classes (like generic containers) are deep copied using<br>the convenient map((x) =&gt; x.copyWith()) strategy.<br>• If you have a list of primitive types (like doubles or int) you can use the []..addAll()<br>shortcut. Do this only with primitive types.</p><p>Flutter Complete Reference</p><p>104</p><p>5 | Inheritance and Exceptions<br>5.1</p><p>Inheritance</p><p>In any OOP language you can create hierarchies of classes and Dart is no exception. Here’s the<br>most basic example we can imagine.<br>class A {}<br>class B extends A {}<br>As you might expect, A is called superclass while B is the subclass (or “child class”). Methods<br>can be overridden in subclasses because they all are “virtual” by default.<br> The term virtual indicates the possibility to redefine the behavior of a method in<br>the subclasses. It’s a very common OOP concept.<br>Actually Dart doesn’t have the virtual keyword but it’s “implicit” because any method can be<br>overridden along the hierarchy. The annotation <a href="http://twitter.com/override">@override</a> is optional but you’d better always<br>use it. Starting from Dart 2.9 onwards, implicit downcasts are not allowed:<br>class A {<br>double test(double a) =&gt; a * 0.5;<br>}<br>class B extends A {<br><a href="http://twitter.com/override">@override</a><br>double test(double a) =&gt; a * 1.5;<br>}<br>Flutter Complete Reference</p><p>105</p><p>Chapter 5. Inheritance and Exceptions<br>void main() {<br>A obj1 = A();<br>A obj2 = B(); // Upcast<br>B obj3 = obj1; // Downcast — ERROR from Dart 2.9</p><p>}</p><p>print(“${obj1.test(1)}”); // Prints 0.5<br>print(“${obj2.test(1)}”); // Prints 1.5</p><p>This behaves in the classic OOP way; obj1 calls the method in class A while obj2 calls the<br>overridden version in class B. When overriding, you can reference the original method definition<br>in the superclass:<br>class B extends A {<br><a href="http://twitter.com/override">@override</a><br>double test(double a) {<br>final original = super.test(a);<br>return original * 1.5;<br>};<br>}<br>The special keyword super holds a reference to the super class. The usage of super.test(a)<br>calls the test() method defined in the superclass. In Java for example, you get the same behavior.<br> You cannot block inheritance since every class can have the extends modifier.<br>In Java for example you can write final class A {} to say “hey, you can’t inherit<br>from me” but in Dart there is no equivalent.<br>You’re allowed to also override setters (set) and getters (get) other than regular methods. Dart<br>doesn’t support multiple inheritance, like C++ does for example, meaning that extends works<br>only with a single class:<br>// Ok<br>class A {}<br>class B extends A {}<br>// Doesn’t work<br>class A {}<br>Flutter Complete Reference</p><p>106</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69ee7d5a78bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Complete Reference:Chapter 1, 2, 3]]></title>
            <link>https://medium.com/@linsaw49/flutter-complete-reference-chapter-1-2-3-a4767484b82d?source=rss-a3278f83f046------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4767484b82d</guid>
            <dc:creator><![CDATA[saw lin]]></dc:creator>
            <pubDate>Tue, 02 Aug 2022 17:03:03 GMT</pubDate>
            <atom:updated>2022-08-02T17:03:04.076Z</atom:updated>
            <content:encoded><![CDATA[<p>Dedicated to Giorgia, my friends and my family.</p><p>a</p><p>Contents<br>1 Welcome<br>1.1 Introduction . . . . . . . . . . . . . .<br>1.1.1 Who is this book for . . . . .<br>1.1.2 Author . . . . . . . . . . . . .<br>1.1.3 Acknowledgments . . . . . . .<br>1.1.4 Online resources and the quiz<br>1.2 Introduction to Dart . . . . . . . . .<br>1.2.1 Supported platforms . . . . .<br>1.2.2 Package system . . . . . . . .<br>1.2.3 Hello World . . . . . . . . . .<br>1.3 Intorduction to Flutter . . . . . . . .<br>1.3.1 How does it work . . . . . . .<br>1.3.2 Why Flutter uses Dart . . . .<br>1.3.3 Hello world . . . . . . . . . .</p><p>I</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>The Dart programming language</p><p>2 Variables and data types<br>2.1 Variables . . . . . . . . . . . . .<br>2.1.1 Initialization . . . . . . .<br>2.1.2 final . . . . . . . . . . .<br>2.2 Data types . . . . . . . . . . . .<br>2.2.1 Numbers . . . . . . . . .<br>2.2.1.1 Good practices<br>2.2.2 Strings . . . . . . . . . .<br>2.2.3 Enumerated types . . . .<br>2.2.3.1 Good Practices<br>Flutter Complete Reference</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>15<br>15<br>16<br>16<br>17<br>17<br>18<br>18<br>22<br>22<br>24<br>24<br>28<br>29</p><p>33<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>35<br>35<br>36<br>37<br>38<br>39<br>40<br>41<br>43<br>44<br>3</p><p>Contents</p><p>2.3<br>2.4</p><p>2.2.4 Booleans . . . . . . . . . .<br>2.2.5 Arrays . . . . . . . . . . .<br>Nullable and Non-nullable types .<br>Data type operators . . . . . . .<br>2.4.1 Arithmetic operators . . .<br>2.4.2 Relational operators . . .<br>2.4.3 Type test operators . . . .<br>2.4.4 Logical operators . . . . .<br>2.4.5 Bitwise and shift operators</p><p>3 Control flow and functions<br>3.1 If statement . . . . . . . . . . .<br>3.1.1 Conditional expressions .<br>3.1.2 Good practices . . . . .<br>3.2 switch statement . . . . . . . .<br>3.3 for and while loops . . . . . . .<br>3.3.1 for-in loop . . . . . . . .<br>3.4 Assertions . . . . . . . . . . . .<br>3.5 Good practices . . . . . . . . .<br>3.6 The basics of functions . . . . .<br>3.6.1 The Function type . . .<br>3.7 Anonymous functions . . . . . .<br>3.8 Optional parameters . . . . . .<br>3.8.1 Named parameters . . .<br>3.8.2 Positional parameters . .<br>3.9 Nested functions . . . . . . . .<br>3.10 Good practices . . . . . . . . .<br>3.11 Using typedefs . . . . . . . . . .<br>4 Classes<br>4.1 Libraries and visibility . . . . .<br>4.1.1 Encapsulation . . . . . .<br>4.1.2 Good practices . . . . .<br>4.2 Constructors . . . . . . . . . . .<br>4.2.1 Initializer list . . . . . .<br>4.2.2 Named constructors . . .<br>4.2.3 Redirecting constructors<br>4.2.4 Factory constructors . .<br>Flutter Complete Reference</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>44<br>45<br>46<br>49<br>49<br>50<br>51<br>52<br>52</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>54<br>54<br>54<br>55<br>56<br>58<br>59<br>60<br>61<br>61<br>63<br>64<br>67<br>67<br>69<br>70<br>71<br>72</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>74<br>76<br>78<br>80<br>80<br>83<br>84<br>85<br>85</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>4</p><p>Contents</p><p>4.3</p><p>4.4<br>4.5<br>4.6</p><p>4.2.5 Instance variables initialization<br>4.2.6 Good practices . . . . . . . . .<br>const keyword . . . . . . . . . . . . . .<br>4.3.1 const constructors . . . . . . . .<br>4.3.2 Good practices and annotations<br>Getters and setters . . . . . . . . . . .<br>4.4.1 Good practices . . . . . . . . .<br>Operators overload . . . . . . . . . . .<br>4.5.1 callable classes . . . . . . . . .<br>Cloning objects . . . . . . . . . . . . .</p><p>5 Inheritance and Exceptions<br>5.1 Inheritance . . . . . . . . . . . . . . .<br>5.1.1 super and constructors . . . . .<br>5.1.2 Abstract classes . . . . . . . . .<br>5.1.3 Interfaces . . . . . . . . . . . .<br>5.1.3.1 extends vs implements<br>5.1.4 Mixins . . . . . . . . . . . . . .<br>5.1.5 Good practices . . . . . . . . .<br>5.2 Extension methods . . . . . . . . . . .<br>5.2.1 Good practices . . . . . . . . .<br>5.3 The Object class . . . . . . . . . . . .<br>5.3.1 Comparable&lt;T&gt; . . . . . . . .<br>5.4 Exceptions . . . . . . . . . . . . . . . .<br>5.4.1 on and catch . . . . . . . . . .<br>5.4.2 finally . . . . . . . . . . . . . .<br>5.4.3 Good practices . . . . . . . . .<br>6 Generics and Collections<br>6.1 Generic types . . . . . . . . . . . . . .<br>6.1.1 Introduction . . . . . . . . . . .<br>6.1.2 Type safety . . . . . . . . . . .<br>6.1.3 Usage . . . . . . . . . . . . . .<br>6.2 Collections . . . . . . . . . . . . . . . .<br>6.2.1 List . . . . . . . . . . . . . . .<br>6.2.1.1 Collection statements<br>6.2.1.2 Implementation . . . .<br>6.2.2 Set . . . . . . . . . . . . . . . .<br>Flutter Complete Reference</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>. 86<br>. 88<br>. 90<br>. 92<br>. 93<br>. 95<br>. 97<br>. 98<br>. 99<br>. 101</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>105<br>105<br>108<br>109<br>111<br>113<br>116<br>120<br>121<br>123<br>124<br>127<br>128<br>129<br>131<br>132</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>136<br>136<br>136<br>137<br>139<br>141<br>141<br>142<br>143<br>145</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>5</p><p>Contents<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>147<br>147<br>149<br>150<br>150<br>153</p><p>7 Asynchronous programming<br>7.1 Introduction . . . . . . . . . . . . .<br>7.2 Futures . . . . . . . . . . . . . . .<br>7.2.1 Comparison . . . . . . . . .<br>7.2.2 async and await . . . . . . .<br>7.2.3 Good practices . . . . . . .<br>7.3 Streams . . . . . . . . . . . . . . .<br>7.3.1 Streams and generators . . .<br>7.3.2 Subscribers . . . . . . . . .<br>7.3.3 Differences . . . . . . . . . .<br>7.3.4 Using a controller . . . . . .<br>7.4 Isolates . . . . . . . . . . . . . . . .<br>7.4.1 Multiple isolates and Flutter</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>157<br>157<br>158<br>161<br>163<br>165<br>166<br>168<br>171<br>174<br>175<br>179<br>184</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>186<br>187<br>187<br>188<br>190<br>191<br>193<br>194<br>196<br>198</p><p>6.2.3<br>6.3</p><p>Good<br>6.3.1<br>6.3.2</p><p>6.2.2.1 Implementation .<br>Map . . . . . . . . . . . .<br>6.2.3.1 Implementation .<br>practices . . . . . . . . . .<br>operator== and hashCode<br>Transform methods . . . .</p><p>8 Coding principles with Dart<br>8.1 SOLID principles . . . . . . . . . . . .<br>8.1.1 Single Responsibility Principle .<br>8.1.2 Open closed principle . . . . . .<br>8.1.3 Liskov Substitution Principle .<br>8.1.4 Interface Segregation Principle .<br>8.1.5 Dependency Inversion Principle<br>8.2 Dependency Injection . . . . . . . . . .<br>8.2.1 Constructor injection . . . . . .<br>8.2.2 Method injection . . . . . . . .</p><p>II</p><p>The Flutter framework</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>201</p><p>9 Basics of Flutter<br>203<br>9.1 Structure and tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203<br>9.1.1 Folder structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205<br>9.1.2 The pubspec.yaml file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206<br>Flutter Complete Reference</p><p>6</p><p>Contents</p><p>9.2</p><p>9.3</p><p>9.4</p><p>9.1.3 Hot Reload . . . . . . . . . . . . . . . .<br>9.1.4 Linter rules . . . . . . . . . . . . . . . .<br>9.1.5 Tree shaking and constants . . . . . . .<br>Widgets and State . . . . . . . . . . . . . . . .<br>9.2.1 Basic widgets . . . . . . . . . . . . . . .<br>9.2.1.1 Text . . . . . . . . . . . . . . .<br>9.2.1.2 Row . . . . . . . . . . . . . . .<br>9.2.1.3 Column . . . . . . . . . . . . .<br>9.2.1.4 ListView . . . . . . . . . . . . .<br>9.2.1.5 Container . . . . . . . . . . . .<br>9.2.1.6 Stack and Positioned . . . . . .<br>9.2.2 Stateless and Stateful widgets . . . . . .<br>9.2.2.1 Good practices . . . . . . . . .<br>9.2.3 Keys . . . . . . . . . . . . . . . . . . . .<br>Rebuilds and optimization . . . . . . . . . . . .<br>9.3.1 const constructor . . . . . . . . . . . . .<br>9.3.2 Prefer widget composition over functions<br>Architecture . . . . . . . . . . . . . . . . . . . .<br>9.4.1 Element and RenderObject . . . . . . .<br>9.4.2 Foreign Function Interface . . . . . . . .<br>9.4.3 Method channels . . . . . . . . . . . . .</p><p>10 Building UIs in Flutter<br>10.1 Material . . . . . . . . . . . . .<br>10.1.1 Scaffold . . . . . . . . .<br>10.1.2 Material widgets . . . .<br>10.1.2.1 Buttons . . . .<br>10.1.2.2 Dialogs . . . .<br>10.2 Cupertino . . . . . . . . . . . .<br>10.2.1 CupertinoPageScaffold .<br>10.2.2 Cupertino widgets . . .<br>10.3 Building layouts . . . . . . . . .<br>10.3.1 Platform support . . . .<br>10.3.1.1 Single OS . . .<br>10.3.1.2 Multiple OSes .<br>10.3.2 Responsive UIs . . . . .<br>10.3.2.1 LayoutBuilder<br>10.3.2.2 MediaQuery . .<br>Flutter Complete Reference</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>210<br>211<br>213<br>215<br>218<br>218<br>219<br>220<br>222<br>223<br>225<br>226<br>231<br>233<br>236<br>237<br>238<br>240<br>243<br>249<br>251</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>255<br>255<br>257<br>260<br>261<br>262<br>266<br>268<br>270<br>272<br>272<br>272<br>274<br>276<br>277<br>280<br>7</p><p>Contents<br>10.3.2.3 Good practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280<br>10.3.3 Scrolling and constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283<br>10.3.4 Using themes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287<br>11 State management<br>11.1 Updating the UI . . . . . . . . . . . . . . . .<br>11.1.1 Considerations . . . . . . . . . . . . .<br>11.1.2 Good practices . . . . . . . . . . . . .<br>11.2 Passing the state with Provider . . . . . . . .<br>11.2.1 Considerations . . . . . . . . . . . . .<br>11.2.1.1 Provider class . . . . . . . . .<br>11.2.1.2 Consumer class . . . . . . . .<br>11.2.2 Good practices . . . . . . . . . . . . .<br>11.3 Alternative to setState: BLoC pattern . . . .<br>11.3.1 Considerations . . . . . . . . . . . . .<br>11.3.1.1 BlocListener class . . . . . . .<br>11.3.2 BlocObserver class . . . . . . . . . . .<br>11.3.3 Persisting the state with HydratedBloc<br>11.3.4 Undo and redo with ReplayBloc . . . .<br>11.3.5 The internals of Bloc: Cubit . . . . . .<br>11.3.6 Good practices . . . . . . . . . . . . .<br>11.4 Good practices for state management . . . . .<br>12 Routes and navigation<br>12.1 Basics of navigation and routing . . . . .<br>12.1.1 Creation of routes . . . . . . . . .<br>12.1.2 The main.dart file . . . . . . . . .<br>12.1.3 The routes.dart file . . . . . . . .<br>12.1.4 Navigating between pages . . . .<br>12.1.5 Good practices . . . . . . . . . .<br>12.1.6 Navigator 2.0 . . . . . . . . . . .<br>12.2 Passing data between pages and widgets<br>12.2.1 The Navigator class . . . . . . . .<br>12.2.2 Passing data with Navigator . . .<br>12.2.3 Passing data with provider . . . .<br>12.3 Other routing techniques . . . . . . . . .<br>13 Localization and internationalization<br>Flutter Complete Reference</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>290<br>291<br>293<br>298<br>299<br>303<br>303<br>304<br>307<br>312<br>318<br>321<br>323<br>324<br>328<br>330<br>333<br>336</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>339<br>339<br>340<br>341<br>342<br>345<br>346<br>348<br>350<br>351<br>352<br>355<br>359<br>363<br>8</p><p>Contents<br>13.1 Introduction . . . . . . . . . . . . . . .<br>13.2 Manual internationalization . . . . . .<br>13.2.1 AppLocalization . . . . . . . . .<br>13.2.2 Localization delegate . . . . . .<br>13.2.3 Backward compatibility . . . .<br>13.3 Internationalizing using intl . . . . . .<br>13.3.1 AppLocalization . . . . . . . . .<br>13.3.2 Localization delegate . . . . . .<br>13.3.3 Plurals and data interpolations<br>13.4 Considerations . . . . . . . . . . . . .<br>14 Animations<br>14.1 Implicit animations . . . . . . .<br>14.2 The animation library . . . . .<br>14.2.1 AnimatedWidget . . . .<br>14.2.2 AnimationBuilder . . . .<br>14.2.2.1 Curves . . . . .<br>14.2.2.2 Tweens . . . .<br>14.3 Custom animations . . . . . . .<br>14.4 Good practices . . . . . . . . .<br>14.4.1 Hero animations . . . .<br>14.4.2 Custom route transitions</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>15 Working with JSON and other formats<br>15.1 Parsing JSON . . . . . . . . . . . . . .<br>15.1.1 Manual parsing . . . . . . . . .<br>15.1.1.1 Parsing lists . . . . . .<br>15.1.1.2 Parsing nested objects<br>15.1.2 Automatic parsing . . . . . . .<br>15.1.2.1 Parsing lists . . . . . .<br>15.1.2.2 Parsing nested objects<br>15.2 Parsing XML . . . . . . . . . . . . . .<br>15.2.1 Parsing strings . . . . . . . . .<br>15.2.2 Building XML strings . . . . .</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>363<br>368<br>368<br>371<br>373<br>375<br>375<br>379<br>380<br>382</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>385<br>385<br>392<br>392<br>397<br>400<br>402<br>405<br>410<br>411<br>413</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>417<br>417<br>418<br>421<br>422<br>423<br>427<br>427<br>429<br>431<br>434</p><p>16 Testing and profiling apps<br>437<br>16.1 Testing Flutter apps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437<br>16.1.1 Unit Test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438<br>Flutter Complete Reference</p><p>9</p><p>Contents<br>16.1.1.1 Testing asynchronous code and streams<br>16.1.1.2 Mocking dependencies . . . . . . . . . .<br>16.1.1.3 Unit testing blocs . . . . . . . . . . . . .<br>16.1.2 Widget Test . . . . . . . . . . . . . . . . . . . . .<br>16.1.2.1 Testing blocs and providers . . . . . . .<br>16.1.3 Integration testing . . . . . . . . . . . . . . . . .<br>16.2 Testing performances . . . . . . . . . . . . . . . . . . . .<br>16.2.1 DevTools . . . . . . . . . . . . . . . . . . . . . .<br>16.2.2 Using the Flutter inspector . . . . . . . . . . . .<br>16.2.3 Using the Timeline view . . . . . . . . . . . . . .<br>16.2.4 Using the Memory view . . . . . . . . . . . . . .<br>16.2.5 Using the Network view . . . . . . . . . . . . . .<br>16.2.6 Using the Logging view . . . . . . . . . . . . . . .<br>16.2.7 Monitoring widget rebuilds . . . . . . . . . . . . .</p><p>III</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>Practical Flutter examples</p><p>17 Networking<br>17.1 Making HTTP requests . .<br>17.1.1 GET requests . . .<br>17.1.2 POST requests and<br>17.1.3 Good practices . .<br>17.2 Working with data . . . .<br>17.2.1 Downloading data .<br>17.2.2 Uploading data . .<br>17.2.3 Good practices . .<br>17.3 Advanced REST API calls<br>17.3.1 Model classes . . .<br>17.3.2 Parsing JSON . . .<br>17.3.3 HTTP Client . . .</p><p>Flutter Complete Reference</p><p>471</p><p>. . . . .<br>. . . . .<br>headers<br>. . . . .<br>. . . . .<br>. . . . .<br>. . . . .<br>. . . . .<br>. . . . .<br>. . . . .<br>. . . . .<br>. . . . .</p><p>18 Assets, images and multimedia<br>18.1 Assets and images . . . . . . . . .<br>18.2 Working with images . . . . . . .<br>18.2.1 Loading from the network<br>18.3 Scalable vector graphics . . . . .<br>18.3.1 Working with SVG files .</p><p>442<br>443<br>447<br>449<br>452<br>453<br>458<br>459<br>459<br>461<br>464<br>466<br>467<br>468</p><p>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>473<br>473<br>473<br>478<br>479<br>481<br>483<br>487<br>490<br>491<br>492<br>494<br>497</p><p>.<br>.<br>.<br>.<br>.</p><p>502<br>502<br>505<br>506<br>510<br>512<br>10</p><p>Contents<br>18.3.2<br>18.4 Audio<br>18.4.1<br>18.4.2</p><p>Loading from the network<br>and video with Flutter . .<br>Playing a video . . . . . .<br>Listening to music . . . .</p><p>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.</p><p>513<br>517<br>517<br>522</p><p>19 Forms and gestures<br>19.1 Forms and validation . . . . . . . . . . .<br>19.1.1 Keyboard and overflows . . . . .<br>19.1.2 Getting the text from a text field<br>19.1.3 Constraining the input . . . . . .<br>19.2 Gestures . . . . . . . . . . . . . . . . . .<br>19.2.1 Swipe to dismiss . . . . . . . . .<br>19.2.2 Dragging items . . . . . . . . . .</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>529<br>529<br>534<br>537<br>539<br>543<br>544<br>548</p><p>20 Interacting with the device<br>20.1 Taking a picture . . . . . . .<br>20.2 Working with sensors . . . .<br>20.3 Working with Geolocation .<br>20.4 Platform-specific packages .<br>20.4.1 Battery level . . . .<br>20.4.2 Device info . . . . .<br>20.4.3 Internet connectivity<br>20.4.4 Shared preferences .</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>555<br>555<br>560<br>563<br>567<br>568<br>568<br>569<br>572</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>573<br>573<br>573<br>577<br>579<br>581<br>584<br>586<br>593<br>593<br>594<br>595<br>596<br>597</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>21 Widgets showcase<br>21.1 Material . . . . . . . . . . . . . . .<br>21.1.1 Drawer . . . . . . . . . . . .<br>21.1.2 BottomNavigationBar . . .<br>21.1.3 NavigationRail . . . . . . .<br>21.1.4 TabBar . . . . . . . . . . .<br>21.1.5 Stepper . . . . . . . . . . .<br>21.1.6 DataTable . . . . . . . . . .<br>21.2 Cupertino . . . . . . . . . . . . . .<br>21.2.1 CupertinoDatePicker . . . .<br>21.2.2 CupertinoActionSheet . . .<br>21.2.3 CupertinoSegmentedControl<br>21.3 Community widgets . . . . . . . . .<br>21.3.1 Flutter Hooks . . . . . . . .<br>Flutter Complete Reference</p><p>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>11</p><p>Contents<br>21.3.2 State notifier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 603<br>22 Using Firebase with Flutter<br>22.1 Installation . . . . . . . . . . . . .<br>22.2 Using Firestore as backend . . . . .<br>22.2.1 Building the backend . . . .<br>22.2.2 Building the frontend . . . .<br>22.2.3 Working with data . . . . .<br>22.2.4 Transactions and batches . .<br>22.3 Monetizing your apps with AdMob<br>22.3.1 Ad banners . . . . . . . . .<br>22.3.2 Rewarded video ads . . . . .<br>22.4 Flutter ML Kit . . . . . . . . . . .<br>22.4.1 Detecting faces . . . . . . .<br>22.4.1.1 CustomPainter and<br>22.4.2 Firebase vision kit . . . . .<br>22.5 Push notifications with FCM . . . .<br>22.5.1 Handling push notifications<br>22.5.2 Sending push notifications .<br>22.6 Authenticating with Firebase . . .<br>22.6.1 Authentication features . . .</p><p>. . . . . . .<br>. . . . . . .<br>. . . . . . .<br>. . . . . . .<br>. . . . . . .<br>. . . . . . .<br>. . . . . . .<br>. . . . . . .<br>. . . . . . .<br>. . . . . . .<br>. . . . . . .<br>the canvas<br>. . . . . . .<br>. . . . . . .<br>. . . . . . .<br>. . . . . . .<br>. . . . . . .<br>. . . . . . .</p><p>23 Publishing packages and apps<br>23.1 Publishing packages on pub.dev . . .<br>23.1.1 Creating the package . . . . .<br>23.1.2 Documenting the code . . . .<br>23.1.3 Reviewing and publishing . .<br>23.1.4 Scores and good practices . .<br>23.1.5 Verified publishers and Flutter<br>23.2 Publishing apps on the stores . . . .<br>23.2.1 Releasing Android apps . . .<br>23.2.2 Releasing iOS apps . . . . . .<br>23.2.3 Splash screens . . . . . . . . .<br>23.2.4 Doing CI/CD for Flutter . . .<br>23.2.4.1 GitHub actions . . .</p><p>. . . . .<br>. . . . .<br>. . . . .<br>. . . . .<br>. . . . .<br>favorite<br>. . . . .<br>. . . . .<br>. . . . .<br>. . . . .<br>. . . . .<br>. . . . .</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>606<br>606<br>610<br>612<br>615<br>619<br>622<br>623<br>625<br>632<br>633<br>634<br>641<br>644<br>645<br>648<br>649<br>653<br>658</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>661<br>661<br>662<br>664<br>667<br>668<br>670<br>672<br>673<br>677<br>679<br>681<br>682</p><p>24 Complete Flutter project example<br>686<br>24.1 Preparing the project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 686<br>Flutter Complete Reference</p><p>12</p><p>Contents<br>24.1.1 Folder structures and basic setup<br>24.2 State management and model classes . .<br>24.2.1 Authentication bloc . . . . . . . .<br>24.2.2 Credentials bloc . . . . . . . . . .<br>24.2.3 Localization files . . . . . . . . .<br>24.3 Building the UI . . . . . . . . . . . . . .<br>24.3.1 Creating the login form . . . . . .<br>24.3.2 Creating the welcome page . . . .<br>24.4 Testing the code . . . . . . . . . . . . . .<br>24.4.1 Unit tests . . . . . . . . . . . . .<br>24.4.2 Widget tests . . . . . . . . . . . .<br>A Dart Appendix<br>A.1 The I/O library . . . .<br>A.1.1 Files . . . . . .<br>A.1.2 Directories . . .<br>A.1.3 Server side Dart<br>A.2 Date and time . . . . .<br>A.3 Obfuscating Dart code</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>B Flutter Appendix<br>B.1 Riverpod . . . . . . . . . . .<br>B.1.1 Usage . . . . . . . .<br>B.1.2 Combining providers<br>B.1.3 Testing . . . . . . . .<br>B.2 Local databases . . . . . . .<br>B.2.1 Hive (NoSQL) . . . .<br>B.2.2 SQLite (SQL) . . . .<br>B.3 Initializing data at startup .<br>B.4 Accessibility . . . . . . . . .<br>B.5 The Flutter community . . .<br>B.6 Flutter SDK management .<br>B.6.1 Web and Desktop . .<br>Index</p><p>Flutter Complete Reference</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>687<br>689<br>693<br>696<br>701<br>702<br>707<br>711<br>712<br>712<br>714</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.</p><p>717<br>717<br>717<br>718<br>719<br>721<br>724</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>727<br>727<br>728<br>734<br>736<br>738<br>738<br>741<br>743<br>745<br>748<br>751<br>752</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.</p><p>755</p><p>13</p><p>Flutter and the related logo are trademarks of Google LLC. We are not endorsed by or affiliated<br>with Google LLC.</p><p>1 | Welcome<br>1.1</p><p>Introduction</p><p>Thank you for having put your faith on this book. If you want to learn how to use a powerful<br>tool that allows developers to quickly create native applications with top performances, you’ve<br>chosen the right book. Nowadays companies tend to consider cross-platform solutions in their<br>development stack mainly for three reasons:<br>1. Faster development: working on a single codebase;<br>2. Lower costs: maintaining a single project instead of many (N projects for N platforms);<br>3. Consistency: the same UI and functionalities on any platform.<br>All those advantages are valid regardless the framework being used. However, for a complete<br>overview, there’s the need to also consider the other side of the coin because a cross-platform<br>approach also has some drawbacks:<br>1. Lower performances: a native app can be slightly faster thanks to the direct contact<br>with the device. A cross-platform framework might produce a slower application due to a<br>necessary bridge required to communicate with the underlying OS;<br>2. Slower releases: when Google or Apple announce a major update for their OS, the maintainers of the cross-platform solution could have the need to release an update to enable<br>the latest features. The developers must wait for an update of the framework, which might<br>slow down the work.<br>Every framework adopts different strategies to maximize the benefits and minimize or get rid of<br>the drawbacks. The perfect product doesn’t exist, and very likely we will never have one, but<br>there are some high quality frameworks you’ve probably already heard:<br>• Flutter. Created by Google, it uses Dart;<br>Flutter Complete Reference</p><p>15</p><p>Chapter 1. Welcome<br>• React Native. Created by Facebook, it is based on javascript;<br>• Xamarin. Created by Microsoft, it uses the C#;<br>• Firemonkey. Created by Embarcadero, it uses Delphi.</p><p>During the reading of the book you will see how Google tries to make the cross-platform development production-ready using the Dart programming language and the Flutter UI framework.<br>You will learn that Flutter renders everything by itself 1 in a very good way and it doesn’t use<br>any intermediate bridge to communicate with the OS. It compiles directly to ARM (for mobile)<br>or optimized JavaScript (for web).</p><p>1.1.1</p><p>Who is this book for</p><p>To get the most out of this book, you should already know the basics of object-oriented programming and preferably at least an “OOP language” such as Java or C#. Our goal is trying<br>to make the contents of this book understandable for the widest possible range of developers.<br>Nevertheless, you should already have a minimum of experience in order to better understand<br>the concepts.<br>If you already know what is a class, what is inheritance and what is nullability, part 1 of this<br>book is going to be a walk in the park. Foreknowledge aside, we will talk about both Dart and<br>Flutter “from scratch” so that the reader can understand any concept regardless the expertise<br>level.</p><p>1.1.2</p><p>Author</p><p>Alberto Miola is an Italian software developer that started working with Delphi (Object Pascal)<br>for desktop development and Java for back-end and Android apps. He currently works in Italy<br>where he daily uses Flutter for mobile and Java for desktop and back-end. Alberto graduated<br>1</p><p>For example, it doesn’t use the system’s OEM widgets</p><p>Flutter Complete Reference</p><p>16</p><p>Chapter 1. Welcome<br>in computer science at University of Padua with a thesis about cross-platform frameworks and<br>OOP programming languages.</p><p>1.1.3</p><p>Acknowledgments</p><p>This book owes a lot to some people the author has to mention here because he thinks it’s the<br>minimum he can do to express his gratitude. They have technically supported the realization<br>of this book with their fundamental comments and critiques that improved the quality of the<br>contents.<br>• Rémi Rousselet. He is the author of the famous “provider” 2 package and a visible<br>member in the Flutter/Dart community. He actively answers on stackoverflow.com helping<br>tons of people and constantly works in the creation of open source projects.<br>• Felix Angelov. Felix is a Senior Software Engineer at Very Good Ventures. He previously<br>worked at BMW for 3 years and is the main maintainer of the bloc state management<br>library. He has been building enterprise software with Flutter for almost 2 years and loves<br>the technology as well as the amazing community.<br>• Matej Rešetár. He is helping people get prepared for real app development on resocoder.com and also on the Reso Coder YouTube channel. Flutter is an amazing framework<br>but it is easy to write spaghetti code in it. That’s why he’s spreading the message of proper<br>Flutter app architecture.<br>Special thanks to my friends Matthew Palomba and Alfred Schilken which carefully read the<br>book improving the style and the quality of the contents.</p><p>1.1.4</p><p>Online resources and the quiz</p><p>The official website of this book 3 contains the source code of the examples described in Part III.<br>While reading the chapters you might encounter this box:<br>B Resources &gt; Chapter 16 &gt; Files download</p><p>2<br>3</p><p><a href="https://pub.dev/packages/provider">https://pub.dev/packages/provider</a><br><a href="https://fluttercompletereference.com/">https://fluttercompletereference.com</a></p><p>Flutter Complete Reference</p><p>17</p><p>Chapter 1. Welcome<br>It indicates that if you navigate to the Resources page of our website, you’ll find the complete<br>source code of the example being discussed at Chapter 16 &gt; Files download. In addition, you<br>can play the “Quiz game” which will test the Dart and Flutter skills you’ve acquired reading this<br>book.</p><p>At the end, the result page will tell you the exact page of the book at which you can find an<br>explanation of the answer.</p><p>1.2</p><p>Introduction to Dart</p><p>Dart is a client-optimized, garbage-collected, OOP language for creating fast apps that run on<br>any platform. If you are familiar with an object oriented programming language such as Java or<br>C# you might find many similarities with Dart. The first part of this book aims to show how<br>the language can help you solving problems and the vastness of its API.</p><p>1.2.1</p><p>Supported platforms</p><p>Dart is a very flexible language thanks to the environment in which it lives. Once the source code<br>has been written (and tested) it can be deployed in many different ways:<br>Flutter Complete Reference</p><p>18</p><p>Chapter 1. Welcome<br>• Stand-alone. In the same way as a Java program can’t be run without the Java Virtual<br>Machine (JVM), a stand-alone Dart program can’t be executed without the Dart Virtual<br>Machine (DVM). There’s the need to download and install the DVM which to execute Dart<br>in a command-line environment. The SDK, other than the compiler and the libraries, also<br>offers a series of other tools:<br>– the pub package manager, which will be explored in detail in chapter 23;<br>– dart2js, which compiles Dart code to deployable JavaScript;<br>– dartdoc, the Dart documentation generator;<br>– dartfmt, a code formatter that follows the official style guidelines.<br>In other words, with the stand-alone way you’re creating a Dart program that can only<br>run if the DVM is installed. To develop Flutter apps for any platform (mobile, web and<br>desktop), instead of installing the “pure” Dart SDK, you need to install Flutter 4 (which is<br>basically the Dart SDK combined with Flutter tools).<br>• AOT compiled. The Ahead Of Time compilation is the act of translating a high-level<br>programming language, like Dart, into native machine code. Basically, starting from the<br>Dart source code you can obtain a single binary file that can execute natively on a certain<br>operating system. AOT is really what makes Flutter fast and portable.</p><p>With AOT there is NO need to have the DVM installed because at the end you get a single<br>binary file (an .apk or .aab for Android, an .ipa for iOS, an .exe for Windows…) that can<br>be executed.<br>– Thanks to the Flutter SDK you can AOT compile your Dart code into a native binary<br>4</p><p><a href="https://flutter.dev/docs/get-started/install">https://flutter.dev/docs/get-started/install</a></p><p>Flutter Complete Reference</p><p>19</p><p>Chapter 1. Welcome<br>for mobile, web and desktop.<br>– As of Flutter 1.21, the Dart SDK is included in the Flutter SDK so you don’t have to<br>install them separately. They’re all bundled in a single install package.<br>– Starting from version 2.6, the dart2native command (supported on Windows, macOS<br>and Linux) makes AOT compiles a Dart program into x64 native machine code. The<br>output is a standalone executable file.<br>AOT compilation is very powerful because it natively brings Dart to mobile desktop. You’ll<br>end up having a single native binary which doesn’t require a DVM to be installed on the<br>client in order to run the application.<br>• Web. Thanks to the dart2js tool, your Dart project can be “transpiled” into fast and<br>compact JavaScript code. By consequence Flutter can be run, for example, on Firefox or<br>Chrome and the UI will be identical to the other platforms.</p><p>AngularDart 5 is a performant web app framework used by Google to build some famous<br>websites, such as “AdSense” and “AdWords”. Of course it’s powered by Dart!<br>So far we’ve covered what you can do with Dart when it comes to deployment and productionready software. When you have to debug and develop, both for desktop/mobile and web, there<br>are useful some tools coming to the rescue.</p><p>5</p><p><a href="https://angulardart.dev/">https://angulardart.dev/</a></p><p>Flutter Complete Reference</p><p>20</p><p>Chapter 1. Welcome</p><p>This picture sums up very well how the Dart code can be used in development and deployment. We’ve just covered the “Deploy” side in the above part, so let’s analyze the “Develop”<br>column:<br>• Desktop/mobile. The Just In Time (JIT) technique can be seen as a “real time translation” because the compilation happens while the program is executing. It’s a sort of<br>“dynamic compilation” which happens while the program is being used.<br>JIT compilation, combined with the DVM (JIT + VM in the picture), allows the dispatch<br>of the code dynamically without considering the user’s machine architecture. In this way<br>it’s possible to smoothly run and debug the code everywhere without having to mess up<br>with the underlying architecture.<br>• Web. The Dart development compiler, abbreviated with dartdevc, allows you to run and<br>debug Dart web apps on Google Chrome. Note that dartdevc is for development only: for<br>deployment, you should use dart2js. Using special tools like webdev 6 there’s the possibility<br>to edit Dart files, refreshing Chrome and visualizing changes almost immediately.<br>As you’ve just seen, Dart can run literally everywhere: desktop, mobile and web. This book will<br>give you a wide overview of the language (Dart version 2.10, with null safety support) and all the<br>required skills to create easily maintainable projects.<br>6</p><p><a href="https://dart.dev/tools/webdev#serve">https://dart.dev/tools/webdev#serve</a></p><p>Flutter Complete Reference</p><p>21</p><p>Chapter 1. Welcome</p><p>1.2.2</p><p>Package system</p><p>Dart’s core API offers different packages, such as dart:io or dart:collection, that expose<br>classes and methods for many purposes. In addition, there is an official online repository called<br>pub containing packages created by the Dart team, the Flutter team or community users like<br>you.</p><p>If you head to <a href="https://pub.dev/">https://pub.dev</a> you will find an endless number of packages for any purpose: I/O<br>handling, XML serialization/de-serialization, localization, SQL/NoSQL database utilities and<br>much more.<br>1. Go to <a href="https://pub.dev/">https://pub.dev</a>, the official repository;<br>2. Let’s say you’re looking for an equation solving library. Type “equations” in the search bar<br>and filter the results by platform. Some packages are available only for Dart, others only<br>for Flutter and a good part works for both;<br>3. The page of the package contains an installation guide, an overview and a guide so that<br>you won’t get lost.<br>You should check the amount of likes received by the community and the overall reputation of<br>the package because those values indicate how mature and healthy the product is. You will learn<br>how to properly write a library and how to upload it to the pub.dev repository in order to give<br>your contribution to the growth of the community.</p><p>1.2.3</p><p>Hello World</p><p>The simplest way you have to run your Dart code is by opening DartPad 7 , an open-source<br>compiler that works in any modern browser. Clicking on “New Pad” you can decide whether<br>creating a new Dart or Flutter project (with latest stable version of the SDK).<br>7</p><p><a href="https://dartpad.dartlang.org/">https://dartpad.dartlang.org/</a></p><p>Flutter Complete Reference</p><p>22</p><p>Chapter 1. Welcome</p><p>It’s the perfect tool for the beginners that want to play with Dart and try the code. If you’re<br>new to the language, start using DartPad (which is absolutely not and IDE). It always has the<br>latest version of the SDK installed and it’s straightforward to use.<br>void main() {<br>// Best food worldwide!<br>print(“pasta pizza maccheroni”);<br>}<br>Like with Java and C++, any Dart program has to define a function called main() which is the<br>entry point of the application. Very intuitively the print() method outputs to the console, on<br>the right of the DartPad, a string. Starting from chapter 2, you’ll begin to learn the syntax and<br>the good practices that a programmer should know about Dart.</p><p>When you develop for real world applications, you’re going to download the whole SDK and use<br>an IDE like IntelliJ IDEA, Android Studio or VS Code. DartPad doesn’t give you the possibility<br>to setup tests, import external packages, add dependencies and test your code.<br>Flutter Complete Reference</p><p>23</p><p>Chapter 1. Welcome</p><p>1.3</p><p>Intorduction to Flutter</p><p>Flutter is an UI toolkit for building natively compiled applications for mobile, desktop and web<br>with a single codebase. At the time of writing this book, only Flutter for mobile is stable<br>and ready for production. Web support is currently in beta while desktop (macOS, Linux and<br>Windows) is in early alpha: they will be covered in a future release of this reference once they<br>will be officially released as stable builds.</p><p>Being familiar with Jetpack compose or React Native is surely an advantage because the concepts<br>of reactive views and “components tree” are the fundamentals of the Flutter framework.</p><p>1.3.1</p><p>How does it work</p><p>This picture shows how a native app interacts with the OS, whether it’s been written in Kotlin<br>(or Java) for Android or Swift (or Objective-C) for iOS. We’re going to use these 2 platforms as<br>examples in this section.</p><p>Flutter Complete Reference</p><p>24</p><p>Chapter 1. Welcome<br>1. The platform, which can be Android or iOS, exposes a series of OEM widgets used by<br>the app to build the UI. Those widgets are fundamental because they give our app the<br>capabilities to paint the UI, use the canvas and respond to events such as finger taps.<br>2. If you wanted to take a picture from your app or use the bluetooth to send a file, there<br>would be the need to communicate with the native API exposed by the platform. For<br>example, using OS-specific APIs, you could ask for the camera service, wait for a response<br>and then start using it.<br>The cross-platform approach is different and it has to be like so. If you want your app to run on<br>both Android and iOS with the same codebase, you can’t directly use OEM widgets and their API<br>because they come from different architectures. They are NOT compatible. On the hardware<br>side however, both are based on the ARM architecture (precisely, v7 and v8) and the most recent versions have 64-bit support. Flutter AOT compiles the Dart code into native ARM libraries.<br> ARM is a family of RISC microprocessors (32 and 64 bit) widely used in embedded systems. It dominates the mobile world thanks to its qualities: low costs, good<br>heat dissipation and a longer battery life thanks to a low power consumption.</p><p>The picture has rectangles on Android and triangles on iOS to indicate that OEM widgets and<br>Flutter Complete Reference</p><p>25</p><p>Chapter 1. Welcome<br>APIs have differences in how they are structured, in how they interact with the app and in how<br>you have to use them. For this reason, cross-platform apps cannot directly “talk” to the underlying environment: they must speak a language that everyone can understand.<br> Try to only think about the runtime environment for a moment. If you wrote a<br>Java Android app, it would be compiled to work with the ART ecosystem (Android<br>RunTime): how could the same binary file work with iOS architecture which is completely different and has no ART?<br>In the above image, squares represents calls made by Java to interact with the ART<br>which is available only in Android and not on iOS. This compatibility problem is<br>solved by cross-platform frameworks.<br>ReactJS is a Reactive web framework which tries to solve the above problem by adding a bridge<br>in the middle that takes care of the communication with the platform. With this approach, the<br>bridge becomes the real starring of the scene it acts like a translator:</p><p>1. The bridge always exposes the same interface to the app so that it doesn’t care anymore<br>about the OS it’s running on;<br>2. The bridge has an implementation of OEMs and APIs for each platform to allow the app<br>to correctly work in many environments. In this way, you have a native app in the sense<br>that it uses the native tools given by the OS, but there’s still an “adapter” in the middle.<br>Flutter Complete Reference</p><p>26</p><p>Chapter 1. Welcome</p><p>As you can see from the picture, the bridge is an abstraction layer between the app the OS in<br>which it’s hosted. Of course, there has to be a bridge for each supported platform but that’s<br>not something you have to deal with because the developers of the framework will take care of<br>creating all of them.<br> If you used a cross-platform framework, you’d just need to care about creating<br>the app with the code and the API exposed by the framework. The implementation<br>of the bridge is already in the internals of the SDK and it’s automatically “attached”<br>to the app in the build phase. You don’t have to create the bridge.<br>The bridge approach is quite popular, but it could be a potential bottleneck that slows down<br>the execution and thus the performances might drop. If you think about animations, swipes or<br>transitions, widgets are accessed very often and many of them running at the same time could<br>slow down the app. Flutter adopts a completely different strategy:</p><p>It uses its own very efficient rendering engine, called Skia, to paint the UI so that OEM widgets<br>are not needed anymore. In this way, the app doesn’t rely on the instruments the OS exposes to<br>draw the interface and you can freely control each single pixel of the screen.<br>• Flutter produces native ARM code for the machine;<br>Flutter Complete Reference</p><p>27</p><p>Chapter 1. Welcome<br>• when launched, the app loads the Flutter library. Any rendering, input or event handling,<br>and so on, is delegated to the compiled Flutter and app code. This is much faster than<br>having a bridge.<br>• A minimal Flutter app is about 4.4 MB on Android and 10.9 MB on iOS (depending on<br>the architecture, whether it be ARM 32 or 64 bit) 8<br>The true power of Flutter lies on the fact that apps are built with their own rendering stuff and<br>they are not constrained to paint the UI following the rules “imposed” by OEM widgets. You’re<br>free to control the screen and manipulate every single pixel.</p><p>1.3.2</p><p>Why Flutter uses Dart</p><p>There are many reasons behind the decision made by Google to choose Dart as language for the<br>Flutter framework. At the time of writing this book, the latest stable version of Dart is 2.9.2<br>(Dart 2.10 is on beta, but downloadable anyway). Here’s a summary 9 of what brought them to<br>make this choice.<br>1. OOP style. The vast majority of developers have object-oriented programming skills and<br>thus Dart would be easy to learn as it adopts most of the common OOP patterns. The<br>developer doesn’t have to deal with a completely new way of coding; he can reuse what he<br>already knows and integrate it with the specific details of Dart.<br>2. Performances. In order to guarantee high performances and avoid frame dropping during<br>the execution of the app, there’s the need of a high performance and predictable language.<br>Dart can guarantee to be very efficient and it provides a powerful memory allocator that<br>handles small, short-lived allocations. This is perfect for Flutter’s functional-style flow.<br>3. Productivity. Flutter allows developers to write Android, iOS, web and desktop apps<br>with a single codebase keeping the same performances, aspect and feeling in each platform. A highly productive language like Dart accelerates the coding process and makes the<br>framework more attractive.<br>4. Both Flutter and Dart are developed by Google which can freely decide what to do with<br>them listening to the community as well. If Dart was developed by another company,<br>Google probably wouldn’t have the same freedom of choice in implementing new features<br>and and the language couldn’t evolve at the desired pace.<br>Another important aspect is that Dart is strongly typed, meaning that the compiler is going<br>8<br>9</p><p><a href="https://flutter.dev/docs/resources/faq#how-big-is-the-flutter-engine">https://flutter.dev/docs/resources/faq#how-big-is-the-flutter-engine</a><br><a href="https://flutter.dev/docs/resources/faq#why-did-flutter-choose-to-use-dart">https://flutter.dev/docs/resources/faq#why-did-flutter-choose-to-use-dart</a></p><p>Flutter Complete Reference</p><p>28</p><p>Chapter 1. Welcome<br>to be very strict about types; you’ll have both less runtime surprises and an easier debugging<br>process. In addition, keep in mind that Dart is a complete swiss-knife because it has built-in<br>support for:<br>• tree-shaking optimization;<br>• hot reload feature;<br>• a package manager with mandatory documentation and the possibility to play with the<br>code using DartPad;<br>• DevTools, a collection of debugging and performance tools;<br>• code documentation generator tool;<br>• support for JIT and AOT compilation.<br>By owning two home-made products, Google can keep the entire projects under control and<br>decide how to integrate them in the best way possible with quick development cycles. Dart<br>evolves together with Flutter and as time goes by: they help each other maximizing productivity<br>and performances.</p><p>1.3.3</p><p>Hello world</p><p>When creating Flutter apps for the production world, you should really consider using Android<br>Studio or VSCode and install the respective plugins. They offer a debugger, hints, a friendly UI<br>and powerful optimization tools we will explore in detail.<br>void main() {<br>runApp(MyApp());<br>}<br>class MyApp extends StatelessWidget {<br>const MyApp();<br>Widget build(BuildContext context) {<br>return MaterialApp(<br>home: Scaffold(<br>body: Center(<br>child: Text(“Flutter app!”),<br>),<br>),<br>Flutter Complete Reference</p><p>29</p><p>Chapter 1. Welcome</p><p>}</p><p>}</p><p>);</p><p>This is a very simple example of a minimal Flutter application. You can notice immediately<br>that there is a void main() { … } function, required by Dart to define the entry point of the<br>program. An UI is a composition of widgets that decorate the screen with many objects; you will<br>learn how to properly use them to create efficient and beautiful designs.</p><p>This is an example of how a simple Flutter app looks identical in two different platforms. In this<br>book we will focus on Android and iOS mobile apps but everything you’re going to learn is also<br>valid for web and desktop because it’s always Flutter. Once you have the code ready, open the<br>console…<br>Flutter Complete Reference</p><p>30</p><p>Chapter 1. Welcome<br>$ flutter build appbundle<br>$ flutter build ios<br>$ flutter build web<br>$ flutter build macos<br>$ flutter build windows<br>$ flutter build linux<br>…and it’s just a matter of running different build commands to get different native binaries of<br>the same app. For more info on Flutter for web and desktop, see the appendix B at the bottom<br>of the book.</p><p>Flutter Complete Reference</p><p>31</p><p>Part I<br>The Dart programming language</p><p>“I’m not a great programmer; I’m just a good programmer<br>with great habits.”<br>Martin Fowler</p><p>33</p><p>2 | Variables and data types<br>2.1</p><p>Variables</p><p>As in any programming language, variables are one of the basics and Dart comes with support for<br>type inference. A typical example of creation and initialization of a variable is the following:<br>var value = 18;<br>var myName = “Alberto”<br>In the example, value is an integer while myName is a string. Like Java and C#, Dart is able to<br>infer the type of the variable by looking at the value you’ve assigned. In other words, the Dart<br>compiler is smart enough to figure out by itself which is the correct type of the variable.<br>int value = 18;<br>String myName = “Alberto”<br>This code is identical to the preceding example with the only difference that here the types have<br>been typed explicitly. There would also be a third valid way to initialize variables, but you should<br>almost never use it.<br>dynamic value = 18;<br>dynamic myName = “Alberto”<br>dynamic can be used with any type, it’s like a “jolly”: any value can be assigned to it and the<br>compiler won’t complain. The type of a dynamic variable is evaluated at runtime and thus, for a<br>proper usage, you’d need to work with checks and type casts. According with the Dart guidelines<br>and our personal experience you should:<br>1. Prefer initializing variables with var as much as you can;<br>2. When the type is not so easy to guess, initialize it explicitly to increase the readability of<br>the code;<br>Flutter Complete Reference</p><p>35</p><p>Chapter 2. Variables and data types<br>3. Use Object or dynamic only if it’s really needed but it’s almost never the case.<br>Actually, we could say that dynamic is not really a type: it’s more of a way to turn off static<br>analysis and tell the compiler you know what you’re doing. The only case in which you’ll deal<br>with it will come in the Flutter part in regard to JSON encoding and decoding.</p><p>2.1.1</p><p>Initialization</p><p>The official Dart guidelines 1 state that you should prefer, in most of the cases, the initialization<br>with var rather than writing the type explicitly. Other than making the code shorter (programmers are lazy!) it can increase the readability in various scenarios, such as:<br>// BAD: hard to read due to nested generic types<br>List&lt;List&lt;Toppings&gt;&gt; pizza = List&lt;List&lt;Toppings&gt;&gt;();<br>for(List&lt;Toppings&gt; topping in pizza) {<br>doSomething(topping);<br>}<br>// GOOD: the reader doesn’t have to “parse” the code<br>// It’s clearer what’s going on<br>var pizza = List&lt;List&lt;Toppings&gt;&gt;();<br>for(var topping in pizza) {<br>doSomething(topping);<br>}<br>Those code snippets use generics, classes and other Dart features we will discuss in depth in the<br>next chapters. It’s worth pointing out two examples in which you want to explicitly write the<br>type instead of inferring it:<br>• When you don’t want to initialize a variable immediately, use the late keyword. It will be<br>explained in detail later in this chapter.<br>// Case 1<br>late List&lt;String&gt; names;<br>if (iWantFriends())<br>names = friends.getNames();<br>else<br>names = haters.getNames();<br>1</p><p><a href="https://dart.dev/guides/language/effective-dart/design#types">https://dart.dev/guides/language/effective-dart/design#types</a></p><p>Flutter Complete Reference</p><p>36</p><p>Chapter 2. Variables and data types<br>If you used var instead of List&lt;String&gt; the inferred type would have been null and that’s<br>not what we want. You’d also lose the type safety and readability.<br>• The type of the variable is not so obvious at first glance:<br>// Is this a list? I guess so, “People” is plural…<br>// but actually the function returns a String!<br>var people = getPeople(true, 100);<br>// Ok, this is better<br>String people = getPeople(true, 100);<br>However, there isn’t a golden rule to follow because it’s up to your discretion. In general var<br>is fine, but if you feel that the type can make the code more readable you can definitely write<br>it.</p><p>2.1.2</p><p>final</p><p>A variable declared as final can be set only once and if you try to change its content later, you’ll<br>get an error. For example, you won’t be able to successfully compile this code:<br>final name = “Alberto”;<br>name = “Albert”; // ‘name’ is final and cannot be changed<br>You can also notice that final can automatically infer the type exactly like var does. This<br>keyword can be seen as a “restrictive var” as it deduces the type automatically but does not<br>allow changes.<br>// Very popular — Automatic type deduction<br>final name = “Alberto”;<br>// Generally unnecessary — With type annotation<br>final String nickName = “Robert”;<br>If you want you can also specify the type but it’s not required. So far we’ve only shown examples<br>with strings, but of course both final and var can be used with complex data types (classes,<br>enums) or methods.<br>final rand = getRandomInteger();<br>// rand = 0;<br>// ^ doesn’t work because the variable is final<br>Flutter Complete Reference</p><p>37</p><p>Chapter 2. Variables and data types<br>The type of rand is deduced by the return statement of the method and it cannot be re-assigned<br>in a second moment. The same advice we’ve given in “2.1.1 Initialization” for var can be applied<br>here as well.<br> Later on in the book we will analyze in detail the const keyword, which is the<br>“brother” of final, and it has very important performance impacts on Flutter.<br>While coding you can keep this rule in mind: use final when you know that, once assigned, the<br>value will never change in the future. If you know that the value might change during the time<br>use var and think whether it’s the case to annotate the type or not. Here’s an example in which<br>a final variable fits perfectly:<br>void main() {<br>// Assume that the content of the file can’t be edited<br>final jsonFile = File(‘myfile.json’).readAsString();</p><p>}</p><p>checkSyntax(jsonFile);<br>saveToDisk(jsonFile, ‘file.json’);</p><p>In this example the variable jsonFile has a content that doesn’t have to be modified, it will<br>always remain the same and so a final declaration is good:<br>• it won’t be accidentally edited later;<br>• the compiler will give an error if you try to modify the value.<br>If you used var the code would have compiled anyway but it wouldn’t have been the best choice.<br>If the code was longer and way more complicated, you could accidentally change the content of<br>jsonFile because there wouldn’t be the “protection” of final.</p><p>2.2</p><p>Data types</p><p>Types in Dart can be initialized with “literals”; for example true is a boolean literal and “test”<br>is a string literal. In chapter 6 we will analyze generic data types that are very commonly used<br>for collections such as lists, sets and maps.<br>Flutter Complete Reference</p><p>38</p><p>Chapter 2. Variables and data types</p><p>2.2.1</p><p>Numbers</p><p>Dart has two type of numbers:<br>• int. 64-bit at maximum, depending on the platform, integer values. This type ranges from<br>-263 to 263 -1.<br>• double. 64-bit double-precision floating point numbers that follow the classic IEEE 754<br>standard definition.<br>Both double and int are subclasses of num which provides many useful methods such as:<br>• parse(string),<br>• abs(),<br>• ceil(),<br>• toString()…<br>You should always use double or int. We will see, with generic types, a special case in which<br>num is needed but in general you can avoid it. Some examples are always a good thing:<br>var a = 1; // int<br>var b = 1.0; // double<br>int x = 8;<br>double y = b + 6;<br>num z = 10 — y + x;<br>// 7 is a compile-time constant<br>const valueA = 7;<br>// Operations among constant values are constant<br>const valueB = 2 * valueA;<br>From Dart 2.1 onwards the assignment double a = 5 is legal. In 2.0 and earlier versions you<br>were forced to write 5.0, which is a double literal, because 5 is instead an integer literal and the<br>compiler didn’t automatically convert the values. Some special notations you might find useful<br>are:<br>1. The exponential representation of a number, such as var a = 1.35e2 which is the equivalent of 1.35 * 102 ;<br>Flutter Complete Reference</p><p>39</p><p>Chapter 2. Variables and data types<br>2. The hexadecimal representation of a number, such as var a = 0xF1A where 0xF1A equals<br>to F1A in base 16 (3866 in base 10).</p><p>2.2.1.1</p><p>Good practices</p><p>Very likely, during your coding journey, you’ll have at some point the need to parse numbers from<br>strings or similar kinds of manipulations. The language comes to the rescue with some really<br>useful methods:<br>String value = “17”;<br>var a = int.parse(value); // String-to-int conversion<br>var b = double.parse(“0.98”); // String-to-double conversion<br>var c = int.parse(“13”, radix: 6); // Converts from 13 base 6<br>You should rely on these methods instead of writing functions on your own. In the opposite<br>direction, which is the conversion into a string, there is toString() with all its variants:<br>String v1 = 100.toString(); // v1 = “100”;<br>String v2 = 100.123.toString(); // v2 = “100.123”;<br>String v3 = 100.123.toStringAsFixed(2); // v3 = “100.12”;<br>Since we haven’t covered functions yet you can come back to this point later or, if you’re brave<br>enough, you can continue the reading. When converting numbers from a string, the method<br>parse() can fail if the input is malformed such as “12_@4.49”. You’d better use one of the<br>following solutions (we will cover nullable types later):<br>// 1. If the string is not a number, val is null<br>double? val = double.tryParse(“12@.3x_”); // null<br>double? val = double.tryParse(“120.343”); // 120.343<br>// 2. The onError callback is called when parsing fails<br>var a = int.parse(“1_6”, onError: (value) =&gt; 0); // 0<br>var a = int.parse(“16”, onError: (value) =&gt; 0); // 16<br>Keep in mind that parse() is deprecated: you should prefer tryParse(). What’s important to<br>keep in mind is that a plain parse(“value”) call is risky because it assumes the string is already<br>well-formed. Handling the potential errors as shown is safer.<br>Flutter Complete Reference</p><p>40</p><p>Chapter 2. Variables and data types</p><p>2.2.2</p><p>Strings</p><p>In Dart a string is an ordered sequence of UTF-16 values surrounded by either single or double<br>quotes. A very nice feature of the language is the possibility of combining expressions into strings<br>by using ${expr} (a shorthand to call the toString() method).<br>// No differences between s and t<br>var s = “Double quoted”;<br>var t = ‘Single quoted’;<br>// Interpolate an integer into a string<br>var age = 25;<br>var myAge = “I am $age years old”;<br>// Expressions need ‘{‘ and ‘}’ preceeded by $<br>var test = “${25.abs()}”<br>// This is redundant, don’t do it because ${} already calls toString()<br>var redundant = “${25.toString()}”;<br>A string can be either single or multiline. Single line strings are shown above using single or<br>double quotes, and multiline strings are written using triple quotes. They might be useful when<br>you want to nicely format the code to make it more readable.<br>// Very useful for SQL queries, for example<br>var query = “””<br>SELECT name, surname, age<br>FROM people<br>WHERE age &gt;= 18<br>ORDER BY name DESC<br>“””;<br>In Dart there isn’t a char type representing a single character because there are only strings. If<br>you want to access a particular character of a string you have to use the [] operator:<br>final name = “Alberto”;<br>print(name[0]); // prints “A”<br>print(name[2]); // prints “b”;<br>Flutter Complete Reference</p><p>41</p><p>Chapter 2. Variables and data types<br>The returned value of name[0] is a String whose length is 1. We encourage you to visit<br>online Dart documentation about strings which is super useful and full of examples.</p><p>2</p><p>the</p><p>var s = ‘I am ‘ + name + ‘ and I am ‘ + (23).toString() + ‘ y.o.’;<br>You can concatenate strings very easily with the + operator, in the classic way that most programming languages support. The official Dart guidelines 3 suggest to prefer using interpolation<br>to compose strings, which is shorter and cleaner:<br>var s = ‘I am $name. I am ${25} years old’;<br>In case of a string longer than a single line, avoid the + operator and prefer a simple line break.<br>It’s just something recommended by the Dart for styling reasons, there are no performance<br>implications at all. Try to be as consistent as possible with the language guidelines!<br>// Ok<br>var s = ‘I am going to the’<br>‘second line’;<br>// Still ok but ‘+’ can be omitted<br>var s = ‘I am going to the’ +<br>‘second line’;<br>Since strings are immutable, making too many concatenations with the + operator might be<br>inefficient. In such cases it’d be better if you used a StringBuffer which efficiently concatenates<br>strings. For example:<br>var value = “”;<br>for(var i = 0; i &lt; 900000; ++i) {<br>value += “$i “;<br>}<br>Each time the + operator is called, value is assigned with a new instance which merges the old<br>value and the new one. In other words, this code creates for 900000 times a new String object,<br>one for each iteration, and it’s not optimal at all. Here’s the way to go:<br>var buffer = StringBuffer();<br>2</p><p><a href="https://dart.dev/guides/libraries/library-tour#strings-and-regular-expressions">https://dart.dev/guides/libraries/library-tour#strings-and-regular-expressions</a><br><a href="https://dart.dev/guides/language/effective-dart/usage#prefer-using-interpolation-to-compose-strings-andvalues">https://dart.dev/guides/language/effective-dart/usage#prefer-using-interpolation-to-compose-strings-andvalues</a><br>3</p><p>Flutter Complete Reference</p><p>42</p><p>Chapter 2. Variables and data types<br>for(var i = 0; i &lt; 900000; ++i)<br>buffer.write(“$i “);<br>var value = buffer.toString();<br>This is much better because StringBuffer doesn’t internally create a new string on each iteration;<br>the string is created only once at the moment in which toString() is called. When you have to<br>do long loops that manipulate strings, avoid using the + operator and prefer a buffer. The same<br>class can also be found in Java and C# for example.</p><p>2.2.3</p><p>Enumerated types</p><p>Also known as “enums”, enumerated types are containers for constant values that can be declared<br>with the enum keyword. A very straightforward example is the following:<br>enum Fruits { Apple, Pear, Grapes, Banana, Orange }<br>void main() {<br>Fruits liked = Fruits.Apple;<br>var disliked = Fruits.Banana;</p><p>}</p><p>print(liked.toString()); // prints ‘Fruits.Apple’<br>print(disliked.toString()); // prints ‘Fruits.Banana’</p><p>Each item of the enum has an associated number, called index, which corresponds to the zerobased position of the value in the declaration. You can access this number by using the index<br>property.<br>enum Fruits { Apple, Pear, Grapes, Banana, Orange }<br>void main()<br>var a =<br>var b =<br>var c =<br>}</p><p>{<br>Fruits.Apple.index; // 0<br>Fruits.Pear.index; // 1<br>Fruits.Grapes.index; // 2</p><p>Note that when you need to use an enum you always have to fully qualify it. Using the name only<br>doesn’t work.<br>Flutter Complete Reference</p><p>43</p><p>Chapter 2. Variables and data types<br>2.2.3.1</p><p>Good Practices</p><p>When you need a predefined list of values which represents some kind of textual or numeric data,<br>you should prefer an enum over a primitive data type. In this way you can increase the readability<br>of the code, the consistency and the compile-time checking. Look at these 2 ways of creating a<br>function (/// is used to document the code):<br>enum Chess { King, Queen, Rook, Bishop, Knight, Pawn }<br>/// METHOD 1. Checks if the piece can move in diagonal<br>bool diagonalMoveC(Chess item) { … }<br>/// METHOD 2. Checks if a piece can move in diagonal: [item] can only be:<br>/// 1. King<br>/// 2. Queen<br>/// 3. Rook<br>/// 4. Bishop<br>/// 5. Knight<br>/// 6. Pawn<br>/// Any other number is not allowed.<br>bool diagonalMoveS(int item) { … }<br>This example should convince you that going for the first method is for sure the right choice.<br>• diagonalMoveC(Chess item). There’s a big advantage here: we’re guaranteed by the<br>compiler that item can only be one of the values in Chess. There’s no need for any<br>particular check and we can understand immediately what the method wants us to pass.<br>• diagonalMoveS(int item). There’s a big disadvantage here: we can pass any number, not<br>only the ones from 1 to 6. We’re going to do extra work in the body because we don’t have<br>the help of the compiler, so we need to manually check if item contains a valid value.<br>In the second case, we’d have to make a series of if conditions to check whether the value ranges<br>from 1 to 6. Using an enum, the compiler does the checks for us (by comparing the types) and<br>we’re guaranteed to work with valid values.</p><p>2.2.4</p><p>Booleans</p><p>You can assign to the bool type only the literals true or false, which are both compile-time<br>constants. Here there are a few usage examples:<br>Flutter Complete Reference</p><p>44</p><p>Chapter 2. Variables and data types<br>bool test = 5 == 0; // false<br>bool test2 = !test; // has the opposite value of test<br>var oops = 0.0 / 0.0; // evaluates to ‘Not a Number’ (NaN)<br>bool didIFail = oops.isNaN;</p><p>2.2.5</p><p>Arrays</p><p>Probably you’re used to create arrays like this: int[] array = new int[5]; which is the way<br>that Java and C# offer. In Dart it doesn’t really work like that because you can only deal with<br>collections: an “array” in Dart is represented by a List&lt;T&gt;.<br> List&lt;T&gt; is a generic container where T can be any type (such as String or a<br>class). We will cover generics and collections in detail in chapter 6. Basically, Dart<br>doesn’t have “arrays” but only generic containers.<br>If this is not clear, you can look at this comparison. In both languages there is a generic container<br>for the given type but only Java has “primitive” arrays.<br>• Java<br>// 1. Array<br>double[] test = new test[10];<br>// 2. Generic list<br>List&lt;double&gt; test = new ArrayList&lt;&gt;();<br>• Dart<br>// 1. Array<br>// (no equivalent)<br>// 2. Generic list<br>List&lt;double&gt; test = new List&lt;double&gt;();<br>In Dart you can work with arrays but they are intended to be instances of List&lt;T&gt;. Lists are<br>0-indexed collections and items can be randomly accessed using the [] operator, which will throw<br>an exception if you exceed the bounds.<br>//use var or final<br>final myList = [-3.1, 5, 3.0, 4.4];<br>final value = myList[1];<br>Flutter Complete Reference</p><p>45</p><p>Chapter 2. Variables and data types<br>A consequence of the usage of a List&lt;T&gt; as container is that the instance exposes many useful<br>methods, typical of collections:<br>• length,<br>• add(T value),<br>• isEmpty,<br>• contains(T value)<br>… and much more.</p><p>2.3</p><p>Nullable and Non-nullable types</p><p>Starting from Dart 2.10, variables will be non-nullable by default (nnbd) which means they’re<br>not allowed to hold the null value. This feature has been officially introduced in June 2020 as<br>tech preview in the dev channel of the Dart SDK.<br>// Trying to access a variable before it’s been assigned will cause a<br>// compilation error.<br>int value;<br>print(“$value”); // Illegal, doesn’t compile<br>If you don’t initialize a variable, it’s automatically set to null but that’s an error because Dart<br>has non-nullability enabled by default. In order to successfully compile you have to initialize the<br>variable as soon as it’s declared:<br>// 1.<br>int value = 0;<br>print(“$value”);<br>// 2.<br>int value;<br>value = 0;<br>print(“$value”);<br>In the first case the variable is assigned immediately and that’s what we recommend to do as much<br>as possible. The second case is still valid because value is assigned before it’s ever accessed. It<br>wouldn’t have worked if you had written this:<br>// OK — assignment made before the usage<br>Flutter Complete Reference</p><p>46</p><p>Chapter 2. Variables and data types<br>int value;<br>value = 0;<br>print(“$value”);<br>// ERROR — usage made before assignment<br>int value;<br>print(“$value”);<br>value = 0;<br>Non-nullability is very powerful because it adds another level of type safety to the language and,<br>by consequence, lower possibilities for the developer to encounter runtime exceptions related to<br>null. For example, you won’t have the need to do this:<br>String name = “Alberto”;<br>void main() {<br>if (name != null) {<br>print(name)<br>}<br>}<br>The compiler guarantees that it can’t be null and thus no null-checks are required. To sum up,<br>what’s important to keep in mind while writing Dart 2.10 code (and above) is:<br>• By default, variables cannot be null and they must always be initialized before being<br>used. It would be better if you immediately initialized them, but you could also do it in a<br>second moment before they ever get utilized.<br>• Don’t do null-checks on “standard” non-nullable variables because it’s useless.<br>In Dart you can also declare nullable types which doesn’t require to be initialized before being<br>accessed and thus they’re allowed to be null. Nullables are the counterpart of non-nullable types<br>because the usage of null is allowed (but the additional type safety degree is lost).<br>int? value;<br>print(“$value”); // Legal, it prints ‘null’<br>If you append a question mark at the end of the type, you get a nullable type. For safety, they<br>would require a manual null checks in order to avoid undesired exceptions but, in most of the<br>cases, sticking with the default non-nullability is fine.<br>// Non-nullable version — default behavior<br>Flutter Complete Reference</p><p>47</p><p>Chapter 2. Variables and data types<br>int value = 0;<br>print(“$value”); // prints ‘0’<br>// Nullable version — requires the ? at the end of the type<br>int? value;<br>print(“$value”); // prints ‘null’<br>Nullable types that support the index operator [] need to be called with the ?[] syntax. null<br>is returned if the variable is also null.<br>String? name = “Alberto”;<br>String? first = name?[0]; // first = ‘A’;<br>String? name;<br>String? first = name?[0]; // first = ‘null’;<br>We recommend to stick with the defaults, which is the usage of non-nullable types, as they’re safer<br>to use. Nullables should be avoided or used only when working with legacy code that depends<br>on null. Last but not least, here are the only possible conversions between nullables and non<br>nullables:<br>• When you’re sure that a nullable expression isn’t null, you can add a ! at the end to convert<br>it to the non-nullable version.<br>int? nullable = 0;<br>int notNullable = nullable!;<br>The ! (called “bang operator”) converts a nullable value (int?) into a non-nullable value<br>(int) of the same type. An exception is thrown if the nullable value is actually null.<br>int? nullable;<br>// An exception is thrown<br>int notNullable = nullable!;<br>• If you need to convert a nullable variable into a non-nullable subtype, use the typecast<br>operator as (more on it later):<br>num? value = 5;<br>int otherValue = value as int;<br>You wouldn’t be able to do int otherValue = value! because the bang operator works<br>only when the type is the same. In this example, we have a num and an int so there’s the<br>need for a cast.<br>Flutter Complete Reference</p><p>48</p><p>Chapter 2. Variables and data types<br>• Even if it isn’t a real conversion, the operator ?? can be used to produce a non-nullable<br>value from a nullable one.<br>int? nullable = 10;<br>int nonNullable = nullable ?? 0;<br>If the member on the left (nullable) is non-null, return its value; otherwise, evaluate and<br>return the member of the right (0).<br>Remember that when you’re working with nullable values, the member access operator (.) is not<br>available. Instead, you have to use the null-aware member access operator (?.):<br>double? pi = 3.14;<br>final round1 = pi.round();<br>final round2 = pi?.round();</p><p>2.4</p><p>// No<br>// Ok</p><p>Data type operators</p><p>In Dart expressions are built using operators, such as + and — on primitive data types. The<br>language also supports operator overloading for classes as we will cover in chapter 4.</p><p>2.4.1</p><p>Arithmetic operators</p><p>Arithmetic operators are commonly used on int and double to build expressions. As you already<br>know, the + operator can also be used to concatenate strings.<br>Symbol</p><p>Meaning</p><p>Example</p><p>+</p><p>Add two values</p><p>2 + 3 //5</p><p>-</p><p>Subtract two values</p><p>2–3 //-1</p><p>*</p><p>Multiply two values</p><p>6 * 3 //18</p><p>/</p><p>Divide two values</p><p>9 / 2 //4.5</p><p>∼/</p><p>Integer division of two values</p><p>9 ~/ 2 //4</p><p>Flutter Complete Reference</p><p>49</p><p>Chapter 2. Variables and data types<br>%</p><p>Remainder (modulo) of an int division</p><p>5 % 2 //1</p><p>Prefix and postfix increment or decrement work as you’re used to see in many languages.<br>int a = 10;<br>++a; // a = 11<br>a++; // a = 12<br>int b = 5;<br> — b; // b = 4;<br>b — ; // b = 3;<br>int c = 6;<br>c += 6 // c = 12<br>As a reminder, both postfix and prefix increment/decrement have the same result but they work<br>in a different way. In particular:<br>• in the prefix version (++x) the value is first incremented and then “returned”;<br>• in the postfix version (x++) the valie is first “returned” and then incremented</p><p>2.4.2</p><p>Relational operators</p><p>Equality and relational operators are used in boolean expression, generally inside if statements<br>or as a stop condition of a while loop.</p><p>Symbol</p><p>Meaning</p><p>Example</p><p>==</p><p>Equality test</p><p>2 == 6</p><p>!=</p><p>Inquality test</p><p>2 != 6</p><p>&gt;</p><p>Greather than</p><p>2 &gt; 6</p><p>Flutter Complete Reference</p><p>50</p><p>Chapter 2. Variables and data types<br>&lt;</p><p>Smaller than</p><p>2 &lt; 6</p><p>&gt;=</p><p>Greater or equal to</p><p>2 &gt;= 6</p><p>&lt;=</p><p>Smaller or equal to</p><p>2 &lt;= 6</p><p>.<br>Testing the equality of two objects a and b always happens with the == operator because, unlike<br>Java or C#, there is no equals() method. In chapter 6 we will analyze in detail how classes<br>can be properly compared by overriding the equality operator. In general here’s how the ==<br>works:<br>1. If a or b is null, return true if both are null or false if only one is null. Otherwise…<br>2. … return the result of == according with the logic you’ve defined in the method override.<br>Of course, == works only with objects of the same type.</p><p>2.4.3</p><p>Type test operators</p><p>They are used to check the type of an object at runtime.<br>Symbol</p><p>Meaning</p><p>Example</p><p>as</p><p>Cast a type to another</p><p>obj as String</p><p>is</p><p>True if the object has a certain type</p><p>obj is double</p><p>is!</p><p>False if the object has a certain type</p><p>obj is! int</p><p>.<br>Let’s say you’ve defined a new type like class Fruit {}. You can cast an object to Fruit using<br>the as operator like this:<br>(grapes as Fruit).color = “Green”;<br>Flutter Complete Reference</p><p>51</p><p>Chapter 2. Variables and data types<br>The code compiles but it’s unsafe: if grapes was null or if it wasn’t a Fruit, you would get an<br>exception. It’s always a good practice checking whether the cast is doable before doing it:<br>if (grapes is Fruit) {<br>(grapes as Fruit).color = “Green”;<br>}<br>Now you’re guaranteed the cast will happen only if it’s possible and no runtime exceptions can<br>happen. Actually, the compiler is smart enough to understand that you’re doing a type check<br>with is and it can do a smart cast.<br>if (grapes is Fruit) {<br>grapes.color = “Green”;<br>}<br>You can avoid writing the explicit cast (grapes as Fruit) because, inside the scope of the<br>condition, the variable grapes is automatically casted to the Fruit type.</p><p>2.4.4</p><p>Logical operators</p><p>When you have to create complex conditional expressions you can use the logical operators:</p><p>Symbol</p><p>Meaning</p><p>!expr</p><p>Toggles true to false and vice versa</p><p>expr1 &amp;&amp; expr2</p><p>Logical AND (true if both sides are true)</p><p>expr1 || expr2</p><p>Logical OR (true if at least one is true)</p><p>.</p><p>2.4.5</p><p>Bitwise and shift operators</p><p>You’ll never use these operators unless you’re doing some low level data manipulation but in<br>Flutter this never happens.<br>Flutter Complete Reference</p><p>52</p><p>Chapter 2. Variables and data types<br>Symbol</p><p>Meaning</p><p>a &amp; b</p><p>Bitwise AND</p><p>a | b</p><p>Bitwise OR</p><p>a ^ b</p><p>Bitwise XOR</p><p>∼a</p><p>Bitwise complement</p><p>a &gt;&gt; b</p><p>Right shift</p><p>a &lt;&lt; b</p><p>Left shift</p><p>Flutter Complete Reference</p><p>53</p><p>3 | Control flow and functions<br>3.1</p><p>If statement</p><p>This is probably the most famous statement of any programming language and in Dart it works<br>exactly as you would expect. The else is optional and it can be omitted when not needed. You<br>can avoid using brackets in case of one-liner statements.<br>void main() {<br>final random = 13;</p><p>}</p><p>if (random % 2 == 0)<br>print(“Got an even number”);<br>else<br>print(“Got an odd number”);</p><p>Conditions must be boolean values. In C++ for example you can write if (0) {…} where zero<br>is evaluated to false but in Dart it doesn’t compile; you have to write if (false) {…}.</p><p>3.1.1</p><p>Conditional expressions</p><p>In Dart there are two shorthands for conditional expressions that can replace the if-else statement:<br>• valueA ?? valueB. If valueA is non-null, valueA is returned; otherwise valueB is evaluated and then returned. If the definition is too verbose, you can understand this syntax by<br>looking at the following example.<br>String? status;<br>Flutter Complete Reference</p><p>// This is null<br>54</p><p>Chapter 3. Control flow and functions<br>// isAlive is<br>if (status !=<br>isAlive =<br>else<br>isAlive =</p><p>a String declared somewhere before<br>null)<br>status;<br>“RIP”;</p><p>Basically we want to know whether status is null or not and then decide the proper value<br>to assign. The same logic can be expressed in another, more concise way:<br>String? status; // This is null<br>String isAlive = status ?? “RIP”;<br>In the example isAlive doesn’t need to be nullable as it’s guaranteed to be initialized with<br>a string. The ?? operator automatically checks if status is null and decides what to do:<br>– status is not null: return status;<br>– status is null: return the provided “default value” at the right of ??<br>It’s a very helpful syntax because it guarantees that a variable is properly initialized avoiding<br>unwanted operations with null.<br>• condition ? A : B;. If condition is true A is returned, otherwise you get B. It’s a pretty<br>common pattern among modern languages so you might already be familiar with it.<br>String status;<br>if (correctAns &gt;= 18)<br>status = “Test passed!”;<br>else<br>status = “You didn’t study enough…”<br>If it looks a bit too verbose, you can rewrite the logic in a more concise way:<br>String status = (correctAns &gt;= 18) ?<br>“Test passed!” : “You didn’t study enough…”;<br>We could call this the “shorter if “ syntax in which you replace the if with the question<br>mark (?) and the else with the colon (:). You can omit parenthesis.</p><p>3.1.2</p><p>Good practices</p><p>Simple boolean expressions are easy to read but complicated ones might require documentation<br>and might also not fit well inside a single if statement like the following:<br>Flutter Complete Reference</p><p>55</p><p>Chapter 3. Control flow and functions<br>if ( (A &amp;&amp; B || C &amp;&amp; !A) || (!(A &amp;&amp; C) || B) ) { … }<br>You might get a headache while trying to figure out what’s going on and there are also no<br>comments at all. In such cases, you probably want to make the code more readable by splitting<br>the conditions:<br>final usefulTestName1 = A &amp;&amp; B || C &amp;&amp; !A;<br>final usefulTestName2 = !(A &amp;&amp; C)<br>if (usefulTestName1 || usefulTestName2 || B) { … }<br>For sure it’s more understandable and another programmer, or yourself in the future, will be very<br>grateful. We also recommend to not underestimate the usefulness of variable names.<br> The point is that you have to keep expressions short and easy to read. Break<br>down long conditions into smaller pieces and give the variables good names to better<br>understand what you want to check.<br>We also recommend the usage of the short if syntax only when there’s one condition or at<br>maximum two short ones. The longer the line is the harder it is to understand.</p><p>3.2</p><p>switch statement</p><p>When you have a series of cases to take into account, instead of using a long chain of if-elses you<br>should go for the switch statement. It can compare many types:<br>1. compile-time constants<br>2. enums<br>3. integers<br>4. strings<br>5. classes<br>Classes must not override == if they want to be compared with this statement. At the bottom<br>there’s a default label used as fallback if none of the previous cases matches the item being<br>compared.<br>Flutter Complete Reference</p><p>56</p><p>Chapter 3. Control flow and functions<br>enum Status { Ready, Paused, Terminated }<br>void main() {<br>final status = Status.Paused;</p><p>}</p><p>switch (status) {<br>case Status.Ready:<br>run();<br>break;<br>case Status.Paused<br>pause();<br>break;<br>case Status.Terminated<br>stop();<br>break;<br>default<br>unknown();<br>}</p><p>If the body of the case is NOT empty you must put a break otherwise your code won’t compile.<br>When you just want a fall-through to avoid code-replication, leave the body empty. Here’s a few<br>examples:<br>• This code is not going to compile because the first case has a body, containing start(),<br>but there isn’t a break.<br>switch (status) {<br>case Status.Ready:<br>start();<br>//missing “break;” here<br>case Status.Paused<br>pause();<br>break;<br>}<br>}<br>• This code instead is fine because the case doesn’t have a body; the method pause() is<br>going to be called when status is ready or paused.<br>Flutter Complete Reference</p><p>57</p><p>Chapter 3. Control flow and functions<br>switch (status) {<br>case Status.Ready:<br>case Status.Paused<br>pause();<br>break;<br>}<br>}<br>The above code is equivalent to…<br>switch (status) {<br>case Status.Ready:<br>pause();<br>break;<br>case Status.Paused<br>pause();<br>break;<br>}<br>}<br>… but you should avoid code duplication which is always bad in terms of code maintenance.<br>When you have two or more cases that must execute the same action, use the fall-through<br>approach.</p><p>3.3</p><p>for and while loops</p><p>The iteration with a for loop is the most traditional one and doesn’t need many explanations.<br>You can omit brackets in case of one-liner statements. The index cannot be nullable (using<br>int? i = 0 doesn’t work).<br>for(var i = 0; i &lt;= 10; ++i)<br>print(“Number $i”);<br>As you’d expect, the output prints a series of “Number (i)” in the console. An equivalent version<br>can be written with a classic while loop:<br>var i = 0;<br>while (i &lt;= 10) {<br>print(“Number $i”);<br>Flutter Complete Reference</p><p>58</p><p>Chapter 3. Control flow and functions<br>++i;</p><p>}</p><p>The language also has the do while loop that always executes at least one iteration because the<br>condition is evaluated only at the end of the cycle.<br>var i = 0;<br>do {</p><p>print(“Number $i”);<br>++i;<br>} while (i &lt;= 10)<br>The difference is that the while evaluates the condition at the beginning so the loop could never<br>start. The do while instead runs at least once because the condition check is placed at the end.<br>If you wanted to alter the flow of the loop you could use:<br>• break. It immediately stops the loop in which it is called. In case of nested loops, only the<br>one whose scope contains break is stopped. For example:<br>for (var i = 0; i &lt;= 3; ++i) {<br>// 1.<br>for(var j = 0; j &lt;= 5; ++j) { // 2.<br>if (j == 5)<br>break;<br>}<br>}<br>In this case only loop 2 is terminated when j is 5 but loop 1 executes normally until i<br>reaches 3. In practical terms, we can say break stops only 1 loop.<br>• continue. It skips to the next iteration and, like we’ve seen before, in case of nested loops<br>it does the jump only for the loop containing it, not the others.</p><p>3.3.1</p><p>for-in loop</p><p>There are some cases in which you want to completely traverse a string or a container and you<br>don’t care about the index. Look at this very easy example:<br>final List&lt;String&gt; friendsList = [“A”, “B”, “C”, “D”, “E”];<br>for(var i = 0; i &lt; friendsList.length; ++i)<br>print(friendsList[i]);<br>Flutter Complete Reference</p><p>59</p><p>Chapter 3. Control flow and functions<br>That’s perfectly fine but you’re using i just to retrieve the element at the i -th position and<br>nothing more. There are no calculations based on the index as it’s just used to traverse the list.<br>In such cases you should do the following:<br>List&lt;String&gt; friendsList = [“A”, “B”, “C”, “D”, “E”];<br>for(final friend in friendsList)<br>print(friend);<br>This version is less verbose and clearer. You’re still traversing the entire list but now, instead of<br>the index i, you have declared final friend that represents an item at each iteration.</p><p>3.4</p><p>Assertions</p><p>While writing the code you can use assertions to throw an exception<br>evaluates to false. For example:</p><p>1</p><p>if the given condition</p><p>// the method returns a json-encoded string<br>final json = getJSON();<br>// if length &gt; 0 is false → runtime exception<br>assert(json.length &gt; 0, “String cannot be empty”);<br>// other actions<br>doParse(json);<br>The first parameter of assert must be an expression returning a boolean value. The second<br>parameter is an optional string you can use to tell what’s gone wrong; it will appear in the IDE<br>error message window if the condition evaluates to false.<br> In release mode, every assert is ignored by the compiler and you’re guaranteed<br>that they won’t interfere with the execution flow. Assertions work only in debug mode.<br>When you hit Run on Android Studio or VS Code your Flutter app is compiled in debug mode<br>so assertions are enabled.<br>1</p><p>Exceptions will be discussed in detail in chapter 5</p><p>Flutter Complete Reference</p><p>60</p><p>Chapter 3. Control flow and functions</p><p>3.5</p><p>Good practices</p><p>Sometimes you have to implement a complicated algorithm and you don’t want to make it even<br>more complex by writing code hard to understand. Here’s what we recommend.<br>• Try to always use brackets, even if they can be omitted, so that you can avoid unexpected<br>behaviors. Imagine you had written this code…<br>// Version 1<br>if (“A” == “A”)<br>if (“B” == “B”)<br>print(“Oh well!”);<br>else<br>print(“Oops…”);<br>… but in reality you wanted to write this, with a better indentation:<br>// Version 2<br>if (“A” == “A”)<br>if (“B” == “B”)<br>print(“Oh well!”);<br>else<br>print(“Oops…”);<br>There’s a high possibility that, at first glance, in version 1 you associated the else to the<br>first if but it’d be wrong! While it may seem obvious, in a complex architecture with<br>thousands of lines you might misread and get tricked.<br>• When you have to traverse an entire list and you don’t care about the position in which<br>you are during the iteration, use a for-in loop. As we’ve already said, it’s less verbose and<br>so more understandable.<br>Use assertions, in particular when you create Flutter apps, to control the behavior of your software. Don’t remove them when you’re ready to deploy the code to the production world because<br>they will be automatically discarded.</p><p>3.6</p><p>The basics of functions</p><p>Functions in Dart have the same structure you’re used to see in the most popular programming<br>languages and so you’ll find this example self-explanatory. You can mark a parameter with final<br>but in practice it does nothing.<br>Flutter Complete Reference</p><p>61</p><p>Chapter 3. Control flow and functions<br>bool checkEven(int value) {<br>return value % 2 == 0<br>}<br>When the body of the function contains only one line, you can omit the braces and the return<br>statement in favor of the “arrow syntax”. It works with expressions and not with statements.<br>// Arrow syntax<br>bool checkEven(int value) =&gt; value % 2 == 0;<br>// Arrow syntax with method calls<br>bool checkEven(int value) =&gt; someOtherFunction(value);<br>// Does NOT work<br>bool checkEven(int value) =&gt; if (value % 2 == 0) … ;<br>The second example is a conditional statement so it doesn’t work with the arrow syntax. The<br>first example instead is still a condition but it’s written as expression and so it works fine.<br>// 1. This function does not return a value<br>void test() {}<br>// 2. No return type so this function returns dynamic. Don’t do this.<br>test() {}<br>When you don’t need a function to return a value, simply make it void like you’d do in Java for<br>example. If you omitted the return type like in (2.), the compiler would automatically append<br>return dynamic at the end of the body.<br>void test() =&gt; print(“Alberto”);<br>Interestingly, if you have a void function with an one-liner body, you can use the arrow syntax.<br>The function doesn’t return anything because of the void but you’re allowed to do it anyway.</p><p> Try to always specify the return type or use void. Avoid ambiguity; you could<br>avoid the return type for laziness (you just don’t want to write void) but someone<br>else could think you’re returning dynamic on purpose.<br>Flutter Complete Reference</p><p>62</p><p>Chapter 3. Control flow and functions</p><p>3.6.1</p><p>The Function type</p><p>Dart is truly an OOP language because even functions are objects and the type is called…<br>Function! A return type is required while the parameters list is optional:<br>// Declare a function<br>bool checkEven(int value) =&gt; value % 2 == 0;<br>void main() {<br>// Assign a function to a variable<br>bool Function(int) checker = checkEven;</p><p>}</p><p>// Use the variable that represents the function<br>print(checker(8)); // true</p><p>It’s nothing new: you’re just writing a type (bool Function(int)), its name (checker) and<br>then you’re assigning it a value (checkEven). You may find this declaration a bit weird because<br>it’s made up of many keywords but it’s a simple assignment. This is a comparison to clarify the<br>idea:<br>• 28: It’s an integer and its type is int.<br>• “Pizza”: It’s a string and its type is String.<br>• bool checkEven(int value) =&gt; …: It’s a function and its type is bool Function(int).<br>This particular syntax is very expressive; you have to declare the return type and the exact order<br>of the type(s) it takes. In other words, signatures must match. If you think it’s too verbose, you<br>can use the typical automatic type deduction you’re getting used to see:<br>bool checkEven(int value)</p><p>=&gt; value % 2 == 0;</p><p>void main() {<br>final checker1 = checkEven;<br>var checker2 = checkEven;</p><p>}</p><p>print(checker1(8)); // true<br>print(checker2(8)); // true</p><p>Both var and final will be evaluated to bool Function(int). There’s still something to say<br>Flutter Complete Reference</p><p>63</p><p>Chapter 3. Control flow and functions<br>about this type but you’ll have to wait until the next chapter where we’ll talk about classes and<br>the special call() method.<br> When you declare a variable you can only write Function(int) name without the<br>return type. However, automatic type deduction is generally the best choice because<br>it reduces a lot the verbosity.<br>It might not seem very useful and we’d agree with you because there is no usage context, at the<br>moment. When you’ll arrive at part 2 of the book you’ll see that the Function type is super<br>handy in Flutter because it’s used to create “function callbacks”.</p><p>3.7</p><p>Anonymous functions</p><p>So far you’ve only seen named functions such as bool checkEven(int value) where checkEven<br>is the name. Dart gives you the possibility to create nameless functions called anonymous functions.<br>void main() {<br>bool Function(int) isEven = (int value) =&gt; value % 2 == 0;</p><p>}</p><p>print(isEven(19)); //false</p><p>This syntax allows you to create functions “on the fly” that are immediately assigned to a variable.<br>If you want an anonymous function with no parameters, just leave the parenthesis blank (). Of<br>course you can use final and var to automatically deduce the type.<br>• Single line. You can use the arrow syntax when you have one-liner statements. This<br>example declares a function with no parameters that returns a double.<br>final anon = () =&gt; 5.8 + 12;<br>• Multiple lines. Use brackets and return when you have to implement a logic that’s longer<br>than one line.<br>final anon = (String nickname) {<br>var myName = “Alberto”;<br>myName += nickname;<br>Flutter Complete Reference</p><p>64</p><p>Chapter 3. Control flow and functions</p><p>};</p><p>return myName;</p><p>We recommend to always write down the type of the parameter even if it’s not required by the<br>compiler. You can decide whether the type has to appear or not. Using final and var is allowed<br>but it doesn’t make much sense.<br>String<br>String<br>String<br>String</p><p>Function(String)<br>Function(String)<br>Function(String)<br>Function(String)</p><p>printName<br>printName<br>printName<br>printName</p><p>=<br>=<br>=<br>=</p><p>(String n) =&gt; n.toUpperCase();<br>(final n) =&gt; n.toUpperCase();<br>(var n) =&gt; n.toUpperCase();<br>(n) =&gt; n.toUpperCase();</p><p>Any variant compiles with success but none of them is the best option, the decision is up to your<br>discretion. Before moving on, we’re going to show a simple scenario you’ll encounter many times<br>in Flutter.<br>// 1.<br>void test(void Function(int) action) {<br>// 2.<br>final list = [1, 2, 3, 4, 5];</p><p>}</p><p>// 3.<br>for(final item in list)<br>action(item);</p><p>void main() {<br>// 4.<br>test(<br>// 5.<br>(int value) { print(“Number $value”); }<br>);<br>}<br>The action parameter commonly known as callback because it executes an action given from the<br>outside.<br>1. This function doesn’t return a value because of the void. The parameter, called action,<br>accepts a void function with a single integer value.<br>2. It’s a simple list of integer values<br>Flutter Complete Reference</p><p>65</p><p>Chapter 3. Control flow and functions<br>3. We iterate through the entire list and, for each item, we call the function.<br>4. test(…); is how you normally call a function<br>5. This is an anonymous function returning nothing (void) and asking for a single integer<br>parameter.<br>The flexibility of callbacks lies on the fact that you can reuse the same function test() with<br>different implementations. The caller doesn’t care about the body of the anonymous function, it<br>just invokes it as long as the signature matches.<br>// The same method (test) outputs different values<br>// because anonymous functions have different bodies<br>test( (int value) =&gt; print(“$value”) );<br>test( (int value) =&gt; print(“${value + 2}”) );<br>You will often encounter the forEach() method on collections, which accepts a callback to be<br>executed while elements are traversed. Again, the same function (forEach()) is reused multiple<br>times regardless the implementation (thanks to callbacks).<br>void main() {<br>// Declare the list<br>final list = [1, 2, 3, 4, 5];<br>// Iterate<br>list.forEach((int x) =&gt; print(“Number $x”));<br>}<br>This is an even shorter way that doesn’t use a for-in loop. You pass an anonymous function to<br>the method and it executes the given action for every item. Pay attention because the documentation suggests to avoid using anonymous functions in forEach() calls.<br> A very handy feature you’ll see very often is the possibility to put an underscore<br>when one or more parameters of a function aren’t needed. For example, in Flutter the<br>BuildContext object is often given as a callback param but it’s not always essential.<br>builder: (BuildContext context) {<br>return Text(“Hello”);<br>}<br>Since the variable context isn’t used, but it must be there anyway to match the<br>method signature, you can use an underscore to “hide” it:<br>Flutter Complete Reference</p><p>66</p><p>Chapter 3. Control flow and functions<br>builder: (_) {<br>return Text(“Hello”);<br>}<br>It’s less code for you to write and the reader focuses more on what’s really important.<br>In case of multiple values that you don’t use, just chain a series of underscores.<br>builder: (_, value, __) {<br>return Text(“$value”);<br>}</p><p>3.8</p><p>Optional parameters</p><p>In Dart function parameters can be optional in the sense that if you don’t provide them, the<br>compiler will assign null or a default value you’ve specified.</p><p>3.8.1</p><p>Named parameters</p><p>In the simplest case, a function can have optional parameters whose names must be explicitly<br>written in order to be assigned. Pay attention to null-safety in case you don’t plan to give the<br>variables a default value.</p><p>Declaration</p><p>Calling</p><p>void test({int? a, int? b}) {<br>print(“$a”);<br>print(“$b”);<br>}</p><p>void main() {<br>// Prints ‘2’ and ‘-6’<br>test(a: 2, b: -6);<br>}</p><p>When calling a function with optional named parameters, the order doesn’t matter but the names<br>of the variables names must be explicit. For example, you could have called test(b: -6, a: 2);<br>and it would have worked anyway. When a parameter is missing, the default value is given:</p><p>Flutter Complete Reference</p><p>67</p><p>Chapter 3. Control flow and functions<br>Declaration</p><p>Calling</p><p>void test({int? a, int? b}) {<br>print(“$a”);<br>print(“$b”);<br>}</p><p>void main() {<br>// Prins ‘2’ and ‘null’<br>test(a: 2);<br>}</p><p>Calling test(a: 2); initializes only a because b, which is omitted, is set to null by the compiler.<br>null is the default value of nullable types. You can manually give a default value to an optional<br>named parameter just with a simple assignment:<br>Declaration</p><p>Calling</p><p>void test({int? a, int b = 0}) {<br>print(“$a”);<br>print(“$b”);<br>}</p><p>void main() {<br>// Prints ‘2’ and ‘0’<br>test(a: 2);<br>}</p><p>Note that b doesn’t need to be nullable anymore thanks to the default value. In Dart 2.9 (an<br>lower) nnbd was not enabled so you were able to successfully compile this code, which initializes<br>both a and b to null:<br>Declaration</p><p>Calling</p><p>// Dart 2.9 and lower<br>void test({int a, int b}) {<br>print(“$a”);<br>print(“$b”);<br>}</p><p>// Dart 2.9 and lower<br>void main() {<br>// Prints ‘null’ and ‘null’<br>test();<br>}</p><p>The required modifier, introduced in Dart 2.10 with nnbd, forces an optional parameter to be set.<br>You won’t be able to compile if a required parameter is not used when calling the function.<br>void test({int a = 0, required int b}) {<br>print(“$a”);<br>print(“$b”);<br>Flutter Complete Reference</p><p>68</p><p>Chapter 3. Control flow and functions<br>}<br>void main() {<br>test(a: 5, b: 3); // Ok<br>test(a: 5);<br>// Compilation error, ‘b’ is required<br>}<br>Even if you had written required int? b you’d have to assign b anyway because it’s required.<br>Version 2.9 of Dart and lower didn’t have this keyword: you had to use instead an annotation<br>which just produced a warning (and not a compilation error) by default.<br>// Dart 2.9 and lower<br>void test({int a = 0, <a href="http://twitter.com/required">@required</a> int b}) {…}<br>In Flutter, for a better readability, some methods only use named optional params together with<br>required to force the explicit name in the code.Y ou can mix optional named parameters with<br>“classic” ones:<br>Declaration</p><p>Calling</p><p>void test(int a, {int b = 0}) {<br>print(“$a”);<br>print(“$b”);<br>}</p><p>void main() {<br>// Prints ‘2’ and ‘3’<br>test(2, b: 3);<br>}</p><p>Optional parameters must stay at the end of the list.<br>// it compiles<br>void test(int a, {int? b}) { }<br>// it doesn’t compile<br>void test({int? a}, int b) { }</p><p>3.8.2</p><p>Positional parameters</p><p>You can also use optional parameters without being forced to write down the name. Optional<br>positional parameters follow the same rules we’ve just seen for named params but instead of using<br>curly braces ({ }) they’re declared with square brackets ([ ]).<br>Flutter Complete Reference</p><p>69</p><p>Chapter 3. Control flow and functions</p><p>Declaration</p><p>Calling</p><p>void test([int? a, int? b]) {<br>print(“$a”);<br>print(“$b”);<br>}</p><p>void main() {<br>// Prints ‘2’ and ‘-6’<br>test(2, -6);<br>}</p><p>All the examples we’ve made for named parameters also apply here. They really have the same<br>usage but the practical difference is that, in this case, the name of the parameter(s) doesn’t have<br>to be written in the function call.</p><p>3.9</p><p>Nested functions</p><p>The language allows you to declare functions inside other functions visible only within the scope<br>in which they’re declared. In other words, nested functions can be called only inside the function<br>containing them; if you try from the outside, you’ll get a compilation error.<br> From a practical side, the scope is the “area” surrounded by two brackets { }<br>This example shows how you can nest two functions, where testInner() is called “outer function” and randomValue() is called “inner function”.<br>void testInner(int value) {<br>// Nested function<br>int randomValue() =&gt; Random().nextInt(10);</p><p>}</p><p>// Using the nested funcion<br>final number = value + randomValue();<br>print(“$number”);</p><p>As we’ve just seen, functions are types in Dart so a “nested function” is nothing more than<br>a Function type assignment. Given this declaration, we’re able to successfully compile the<br>following:<br>void main() {<br>Flutter Complete Reference</p><p>70</p><p>Chapter 3. Control flow and functions</p><p>}</p><p>// testInner internally calls randomValue<br>testInner(20);</p><p>An error is going to occur if we try to directly call randomValue from a place that’s not inside<br>the scope of its outer function.<br>void main() {<br>// Compilation error<br>var value = randomValue();<br>}</p><p>3.10</p><p>Good practices</p><p>Following the official Dart guidelines 2 we strongly encourage you to follow these suggestions in<br>order to guarantee consistency with what the community recognizes as a good practice.<br>• Older versions of Dart allow the specification of a default value using a colon (:); don’t do<br>it, prefer using =. In both cases, the code compiles successfully.<br>// Good<br>void test([int a = 0]) {}<br>// Bad<br>void test([int a : 0]) {}<br>The colon-initialization might be removed in the future.<br>• When no default values are given, the compiler already assigns null to the variable so you<br>don’t have to explicitly write it.<br>// Good<br>void test({int? a}) {}<br>// Bad<br>void test({int? a = null}) {}<br>In general, you should never initialize nullables with null because the compiler already<br>does that by default.<br>2</p><p><a href="https://dart.dev/guides/language/effective-dart/usage#functions">https://dart.dev/guides/language/effective-dart/usage#functions</a></p><p>Flutter Complete Reference</p><p>71</p><p>Chapter 3. Control flow and functions<br>Dart gives the possibility to write only the name of a function, with no parenthesis, and automatically pass proper parameters to it. It’s a sort of “method reference”. We are going to convince<br>you with this example:<br>void showNumber(int value) {<br>print(“$value”);<br>}<br>void main() {<br>// List of values<br>final numbers = [2, 4, 6, 8, 10];<br>// Good<br>numbers.forEach(showNumber);</p><p>}</p><p>// Bad<br>numbers.forEach((int val) { showNumber(val); });</p><p>The bad example compiles but you can avoid that syntax in favor of a shorter one.<br>• The forEach() method asks for a function with a single integer parameter and no return<br>type (void).<br>• The showNumber() function accepts an integer as parameter and returns nothing (void).<br>The signatures match! If you pass the function name directly inside the method, the compiler<br>automatically initializes the parameters. This tear-off is very useful and you might already have<br>seen it somewhere else under the name of “method reference” (Java).</p><p>3.11</p><p>Using typedefs</p><p>The typedef keyword simply gives another name to a function type so that it can be easily<br>reused. Imagine you had to write a callback function for many methods:<br>void printIntegers(void Function(String msg) logger) {<br>logger(“Done.”);<br>}<br>void printDoubles(void Function(String msg) logger) {<br>Flutter Complete Reference</p><p>72</p><p>Chapter 3. Control flow and functions</p><p>}</p><p>logger(“Done.”);</p><p>Alternatively, rather than repeating the declaration every time, which leads to code duplication,<br>you can give it an alias using the typedef keyword.<br>typedef LoggerFunction = void Function(String msg);<br>void printIntegers(LoggerFunction logger) {<br>logger(“Done int.”);<br>}<br>void printDoubles(LoggerFunction logger) {<br>logger(“Done double.”);<br>}<br>You are going to encounter this technique very often, especially in Flutter, in callbacks for classes<br>or methods. For instance, VoidCallback 3 is just a function alias for a void function taking no<br>parameters.<br>typedef VoidCallback = void Function();<br>In a future version of Dart, probably later than 2.10, typedef will also be used to define new<br>type names. At the moment it’s not possible, but in the future there will be the possibility to<br>compile the following code:<br>typedef listMap = List&lt;Map&lt;int,double&gt;&gt;;<br>The reason is that generic types can become very verbose and so an alias could improve the<br>readability. Currently, typedef only works with functions.</p><p>3</p><p><a href="https://api.flutter.dev/flutter/dart-ui/VoidCallback.html">https://api.flutter.dev/flutter/dart-ui/VoidCallback.html</a></p><p>Flutter Complete Reference</p><p>73</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4767484b82d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>