S Sinha Beginning Flutter 3 0 with Dart A Beginner to Pro Learn how to build Advanced Flutter Apps (2022)[EN] Beginning Flutter 3 0 with Dart A Beginner to Pro Learn how to build Advanced Flutter 3 0[.]
Trang 2A Beginner to Pro Learn how to build Advanced Flutter 3.0 Apps
Sanjib Sinha
This book is for sale athttp://leanpub.com/beginningflutterwithdart
This version was published on 2022-05-29
This is aLeanpubbook Leanpub empowers authors and publishers with the Lean Publishingprocess.Lean Publishingis the act of publishing an in-progress ebook using lightweight tools andmany iterations to get reader feedback, pivot until you have the right book and build traction onceyou do
© 2020 - 2022 Sanjib Sinha
Trang 3Geolocator plugin makes our life easier 912
What is asynchronous programming? 915
What is Future in Flutter? 916
What are async and await? 917
Flutter State: WithHer App – Step 2 919
API Flutter: WithHer App – Step 3 923
What is an API? 923
How can we use API in Flutter? 924
JSON Flutter: WithHer App – Step 4 928
What is JSON in Flutter? 928
Future Then: WithHer App – Step 5 935
What is Future.then() method? 936
The difference between Future then and async, await 939
Future in Flutter: WithHer App – Step 6 941
What is Future in Flutter? 941
Display data with Future in Flutter 945
Pass data to State Flutter: Final Weather App 948
Passing data from a Stateful Widget 950
Pass data to a State object in Flutter 952
20 Building Two Flutter Chat Apps with Firebase, and Firestore - First app with Stateful Widget, Second App with Provider 957
Chat App with Stateful widget – Step One 957
Is Flutter and Firebase full stack? 963
Is Firebase easy to learn? 963
How to Initialise Chat App and Avoid Errors 965
What is Firebase in Flutter? 965
Initialise App and avoid errors 966
Firebase Chat App authentication 967
How Firebase authentication works 969
Stateful Chat App Final Step 982
How does Firestore work in Flutter? 982
How do you fetch data from Firestore database in Flutter? 985
Flutter Chat app with Provider, Firebase and Firestore 991
Firebase, Firestore rules for Flutter Chat App 1006
Firestore collection rules playground 1006
How to deal with the Business logic 1008
The Business Logic and Provider 1008
The Authentication flow 1013
Flutter Chat app UI: designing the pages 1017
How Flutter Chat app UI works 1021
Chat Apps for Android with Flutter and Firebase 1022
Trang 444 I am an Employee Object with name X
45 I am a variable, I can change my value But I cannot change my Type.
46 I am a variable, so I am changing my value But I cannot change my Type.
47
48 */
Please read the comments we have written in the above code
That will explain many things
A Few Words About DART IDE
We need a good Integrated Development Environment or IDE to build Application in DartProgramming Language
We can use any good IDE
However, our first choice is Visual Studio Code
Visual Studio Code is a source-code editor made by Microsoft for Windows, Linux and macOS
It has many features Most importantly we can debug our code And besides, it has support forsyntax highlighting, intelligent code completion, snippets, code refactoring, and embedded Git.The Android Studio is also good Even you can download and install the IntelliJ IDEA CommunityEdition
To test our code, we also need to install Dart SDK in our local system
If you install Flutter and Dart plugin in any IDE, that will also work In that case, you don’t needDart SDK in your Operating System
Installing any IDE in Windows is comparatively easy Download the “.exe” file from the official website and double-click to launch it
This is recommended You can also download the ZIP file and unpack it to the program files Youwill find the android-studio bin folder where you can launch the respective “.exe” files
However, downloading the “.exe” file from the official web site and launching it online is mended
recom-Installing Android Studio on MAC is not a complicated process
You need to launch Android Studio DMG file and then drag and drop the Android Studio into theApplications folder After that, the launching process is easy
The set-up Wizard will guide you through the rest part For development, you need to download theAndroid SDK components
I will recommend to use Linux as the main operating system
Trang 5More than one Constructor 191
Changing the UI of the Flutter projects 193
What are constraints in flutter 202
What are BoxConstraints in Flutter 207
What is widget in Flutter 212
What is element in Flutter 214
5 How to build Flutter UI using Widgets 217
Common Widgets in Flutter 217
Powerful Basic Widgets 221
Anonymous Functions: Lambda, Higher Order Functions, and Lexical Closures 241
Exploring Higher-Order Functions 243
Inheritance and Mixins in Dart 243
Mixins: Adding more Features to a Class 245
6 Layouts in Flutter, Tips and Tricks 248
Customize child Widgets 252
Layout mechanism of Flutter 257
Library of layout widgets 275
Abstract Class and Methods 282
Advantage of Interfaces 284
Static Variables and Methods 285
The ‘Closure’ is a Special Function 286
Data Structures and Collections 289
Lists: Fixed Length and Growable 290
Set: An Unordered Collections of Unique Items 292
Maps: the Key, Value Pair 295
Queue is Open-Ended 297
Callable Classes 299
Exception Handling 299
Dart Packages and Libraries 302
7 Introduction to State Management and Form Validation in Flutter and Dart 306
State is mutable 307
Life cycle of State 312
Role of Controller in TextField Widget 319
How List and Map used in StateFul DropdownButton Widget 326
How to Valiadate a Form using State Management 328
8 Provider: A recommended approach to manage State and Model-View-Controller Pattern 337
Different approaches to state management 338
A Step by Step guide to use Provider 338
Trang 6Riverpod, another state management package, Riverpod migration, WidgetRef ref, and
What is new in Riverpod 361
Why we need the latest Flutter and Dart SDK? 363
Is Riverpod better than Provider? 364
What is a WidgetRef? 365
Model class with StateNotifierProvider in new Riverpod 368
Model-View-Controller Patterns 371
9 Everything about Flutter Navigation and Route 390
Why do you use onGenerateRoute in flutter? 390
How do you use onGenerateRoute in Flutter? 391
How to use a dynamic initial route? 391
What is Flutter Navigation and how does Flutter Navigator work? 392
How do you pass data from one class to another in flutter? 396
What is enum in Dart flutter? How to use enum in Flutter? 400
How do you change the theme on Flutter? 403
How do you name a route in Flutter? 404
How do you pass data from one screen to another in flutter? 408
How do you make a Flutter app from scratch? 412
10 More on Flutter UI, List, Map, and Provider Best Practices 418
How do you use decoration in a container in Flutter? 418
What is a RichText in flutter? 421
Stateful vs Stateless Flutter 425
What is GridTile Flutter? How do you use grid tiles in Flutter? 431
What is change notifier provider in Flutter? 435
How do you change the font on flutter? 439
How do I store persistent data in Flutter? 443
What is data model in Flutter? 449
How do you pass data between screens in flutter? 454
How do you pass data with provider in Flutter? 460
What is provider pattern Flutter? 468
How do you use ChangeNotifierProvider in Flutter? 473
What is ChangeNotifierProvider value? 480
What is navigator and route in Flutter? 485
How do you pass arguments in Navigator pushNamed? 488
11 Google’s Flutter 2.5 and Dart 2.14, What’s New 493
What is MaterialBanner? 493
How do you Map a dart list in Flutter 2.5? 496
How to start with an app template in Flutter 2.5 504
The latest version of Flutter comes with many new features 507
How do you do localization in flutter 2.5? 512
How do you pass data to a widget in flutter 2.5? 514
Trang 7How to Pass and Receive data in Flutter 2.5 518
12 Understanding Material Design in Flutter 526
What is Material Design in flutter? 526
AppBar Flutter: How Do I use AppBar? 530
How do I use BottomNavigationBar in flutter? 536
What is a drawer in flutter? 542
What is Material App in Flutter? 548
What is a theme in Flutter? 554
What is scaffold in Flutter? 563
How do you make a TabBar in flutter? 572
How do I create a DropdownButton in flutter? 579
What is Material State in Flutter? 582
How do I add a checkbox in flutter? 584
How do I use a checkbox widget in flutter? 588
What is elevated Button in flutter? 591
What is text button in Flutter? 595
What is outlined button in flutter? 598
How do you use the icon button flutter? 601
How do you use a TextField in Flutter? 605
How do you make a flutter card? 610
What is the grid view in Flutter? 613
What is GridView count in flutter? 615
What is GridView.extent in Flutter? 620
How do you use chip in flutter? 624
13 Slivers and Scrolling Widgets 630
What is SliverAppBar in flutter? 630
How do I make my collapsing toolbar flutter? 633
What is SliverGrid in flutter? 636
SliverPersistentHeader Flutter, a sliver whose size varies 641
How do you use slivers flutter? 645
How to use CustomScrollView in Flutter? 648
How to use NestedScrollView in flutter? 652
How to use PageView in Flutter 656
What is PageView builder in flutter? 659
What is PageView custom in flutter? 663
How to use DraggableScrollableSheet 666
Flutter Scrollbar Interactive 674
How to use Scrollbar in flutter 681
How to use ReorderableListView 686
How to rearrange list in flutter 691
What is Scrollable in flutter 695
Trang 8What is ListView in flutter 697
What is ListView builder in flutter 701
What is ListView separated 705
What is ListView custom 709
What is single child ScrollView in flutter 714
14 A Close Encounter with Provider package and State Management 720
What is provider in Flutter? 720
What is Consumer Flutter? 729
What is Flutter Selector? 737
How to use Selector Flutter 742
What is Flutter Selector child 748
15 User Interface, Style, Theme and App Design 757
What are constraints in flutter 757
What are BoxConstraints in Flutter 761
What is widget in Flutter 767
What is element in Flutter 769
What is Align in Flutter 771
How to use aspect ratio widget 775
What is Baseline in Flutter 777
How to use theme in Flutter 782
How to use theme with Provider on flutter 786
16 Flutter 2.8, Future, await, async and Database 793
What is new in Flutter 2.8 793
Future, await and async 796
Which database we use in Flutter 799
SQLite Database and Flutter 807
17 Create, Retrieve, Update and Delete with SQLite Database: Build A Blog and My Diary Application in Flutter 820
SQLite Blog in Flutter: First Part 820
SQLite Blog, Flutter: Second Part 829
SQLite Blog, Flutter: Final Part 840
18 Scoped Model, Provider, SQLite Database and FutureBuilder 862
SQLite with Provider in Flutter 862
What is Scoped Model in flutter 874
Scoped Model and SQLite in Flutter 888
What is future builder in Flutter 898
19 Future then, aync, await, API, JSON: Let’s build a Current Weather Tracker App 911
Future Flutter: WithHer App – Step 1 911
Trang 928 var personOne = Person( "John" );
29 var robotOne = Robot( "ROBO_COP" );
30 print ( "The first person object has a name : ${personOne.name}" );
31 print ( "The first robot object has a name : ${robotOne.name}" );
Trang 1021 What Next? 1028
Trang 11Before getting started, let me tell you one thing Always use the latest Provider package
-https://pub.dev/packages/provider¹ for state management And always maintain the Null Safety
-https://flutter.dev/docs/null-safety²
I also strongly recommend to read the latest and updated articles on Flutter - https://sanjibsinha.com/category/flutter/
³
Download latest Flutter 3.0
To start with, we need to download the Flutter framework
That is our first task We need to go toThe installation page of Flutter -
https://flutter.dev/docs/get-started/install⁴page from where we will download and install Flutter according to your operating
system
If you have been working with Flutter 2.*, then just issue the following command:
1 flutter upgrade
However, Flutter gets updated and upgraded quite often For example, Text Buttons to take inputs
from users are no longer the same now
We will start with Windows, first
Want to read more old and archived Flutter related Articles and resources?
For more old and archived Flutter related Articles and Resources⁵
Before that we want to make one thing clear
What is new in Flutter 3.0
A few days ago Google announced the official release of Flutter 3.0 Let’s see what is new in Flutter
Trang 12Firstly, with reference to mobile application development, there has not been a great change.Structurally what we have been doing, will continue to do.
Certainly a change in here and there had taken place In the next section we’ll discuss that and willtake a deep dive
Secondly, flutter web sections have got the makeover Certainly it has become better
Finally, a lot of changes have taken place in the desktop part
Three months ago Google Flutter and Dart team announced Flutter support for Windows
Flutter 3.0 is stable for macOS and Linux.
With reference to macOS and Linux, a lot of changes have taken place
Now it’s ready for production on all desktop platforms As a result, we can now create rendered menu bars on macOS To do that we can use the “PlatformMenubar” widget that insertsplatform-only menus
platform-It also supports accessibility services such as screen-readers, accessible navigation, and invertedcolours
Full support for international text input on all desktop platforms is also there
Web updates in flutter 3.0
Let’s talk about the Web updates in flutter 3.0.The “ImageDecoder” API plays an important role inweb applications
Therefore flutter web now uses the “ImageDecoder” API in browsers that support it
And there are more
We can also use other widgets in flutter web
For example we can think of the splash screen, loading indicator etc
Most importantly, Flutter 3.0 has improved the performance
It is faster than before
As an outcome it builds frames 20 percent faster which is a significant progress
Last but not least, we should mention two interesting things that have caught our attention
Firstly, Flutter 3.0 supports foldable mobile devices Secondly, Flutter 3.0 supports Material Design3
In the next section we’ll talk about it in detail
Trang 13Figure 3.2 – Scaffold() class constructor empty
We could have only passed the Text() class constructor Widget with a message inside the Scaffold()Widget That would also give us an output, where no styling would have maintained
The following image (Figure 3.3) gives us an idea
Trang 14Figure 1.1 – Downloading Flutter for Windows
We have kept the extracted flutter folder there and created a new ‘environment’ path for the user.Because we want to work through the command prompt, in future, we have created this globalenvironment path Creating a new environment variable path in any Windows operating system isalso easy In the Windows 10 operating system, we type ‘environment variable’ in the search prompt,
it will automatically open up the related window for us
We can copy and paste the whole path there as the following:
1 “ C:\Users\Downloads\flutter\bin ”
Figure 1.2 – Creating the new environment variable path in Windows 10
Trang 15Now, we can open the command prompt and type ‘flutter doctor’ to see whether we have any Flutterrelated IDE installed already It will also check whether we have any connected device or not.
We have not installed Android Studio or any other Flutter related IDE beforehand The command
‘flutter doctor’ has detected that (Figure 1.3)
To work with Flutter, we need a good IDE In fact, when we were downloading Flutter, it indicatedthat we should install Android Studio or any good IDE where we would have a connected device.The connected device is nothing but a virtual mobile device where we can see and test our mobileapplication
Android Studio should be the best choice It is widely used and Flutter home page also suggests todownload and install that IDE
Figure 1.3 – Flutter Doctor Summary in Windows 10
In Flutter Doctor summary, we have found that Android Studio has not been installed and there is
no device available
We will do that in our macOS and Linux machines, because we will use any one of that operatingsystem to learn Flutter and Dart together
Flutter for macOS and Linux
Downloading Flutter for macOS and Linux is same It will download the stable.tar.xz” file in your “Downloads” folder
“flutter_linux_1.17.2-Next we will issue the following command to extract Flutter, on our terminal:
Trang 16Inside that we can keep a collection of data.
We will discuss more about ‘collection’ and data structure when times comes Until then, we willremember that in a collection of data structure, we can keep more than one data
The next code snippet will clear the picture:
Trang 18latest at the time of writing this book We have also installed IntelliJ IDEA Community Edition, and
we have also Visual Studio Code IDE
We can use the virtual device from Android Studio, but we can use the Visual Studio Code IDE orIntelliJ IDEA Community Edition IDE for writing our code They will automatically synchronizewith the connected device
Once you have installed, please check the Flutter latest version and issue the following command:
1 flutter upgrade
However, before that we need to create our first flutter project with the help of flutter command asthe following:
1 //code 1.6
2 flutter create my_first_flutter_app
Remember one thing When we want to create a new flutter project, we should always create likethis The naming convention is important here We can only use the underscore between the words
No hyphen or space is allowed
Now the time has come to go back to the Android Studio We will pick up the ‘open folder’ optionand choose to open the newly created flutter project We have named it as: ‘my_first_flutter_app’
Figure 1.5 – Open the Android Virtual Device (AVD) manager from tools menu
Trang 19To open up the connected device, we need to open the Android Virtual Device manager, or AVDmanager in short.
You will get that from the ‘tools’ menu
Select any one of them and click the ‘green’ play button on the far right hand side of any virtualdevice It will automatically open up the ‘connected device’ (Figure 1.6)
Figure 1.6 – We have the connected device on which we can test our first mobile application
Now everything is ready We can start building our first mobile application from scratch using Flutterand Dart Before closing down this section, we should know a few good tips Usually, the beginnersencounter a few errors when they try to run the command:
1 flutter doctor
If it gives any error, try this command:
1 flutter doctor android-licenses
It will ask you to accept the license Accept it, and it will not give any error anymore Anotherproblem often gives trouble to the new developers
As a beginning Flutter developer, people often are stuck with this issue They cannot launch thevirtual mobile device while working with Android Studio
We want that every code we write should reflect on the virtual device It can be done by going
to the ‘AVD manager’ from tools But sometimes an ugly error pops up its head and tells that
Trang 2013 else print( "You have not touched any button." )
14 if(fourthButtonTouch) print("The giant wakes up." )
15 else print( "You have not touched any button." )
16 }
17
18 //output of code
19 The giant starts running.
20 You have not touched the second button.
21 Touch any button to start the game.
22 The giant goes to sleep.
23 You have not touched any button.
Now you can make this small code snippet more complicated
1 //code 4.2
2 main(List< String > arguments) {
3 bool firstButtonTouch = true ;
4 var firstButtonUntouch;
5 bool secondButtonTouch = false ;
6 bool thirdButtonTouch = true ;
7 bool fourthButtonTouch = false ;
8 firstButtonUntouch ?? = firstButtonTouch;
9 firstButtonUntouch = false ;
10 if (firstButtonUntouch == false || firstButtonTouch == true ) print ( "The giant is sle\
11 eping." );
12 else print("You need to wake up the giant Touch the first button." );
13 if(firstButtonTouch == true && firstButtonUntouch == false ) print ( "The giant starts \
14 running." );
15 print ( "To stop the giant please touch the second button." );
16 if((secondButtonTouch == true && thirdButtonTouch == true ) || fourthButtonTouch == f\
17 alse) print ( "The giant stops." );
18 else print("You have not touched the second button." );
19 print ( "Touch any button to start the game." );
20 if(thirdButtonTouch) print ( "The giant goes to sleep." );
21 else print("You have not touched any button." );
22 if(fourthButtonTouch) print ( "The giant wakes up." );
23 else print("You have not touched any button." );
24 }
According to your complexity of code, you should arrange your ‘if and else’ logic And your outputvaries
Trang 211 //output
2 The giant is sleeping.
3 The giant starts running.
4 To stop the giant please touch the second button.
5 The giant stops.
6 Touch any button to start the game.
7 The giant goes to sleep.
8 You have not touched any button.
For ‘if and else’ logic always remember these golden rules 1 1 When both conditions are true, theresult is true 2 2 When both conditions are false, the result is false 3 3 When one condition is trueand the other condition is false, the result is false 4 4 When one condition is true or one condition
is false, the result is true
In the above code, I just try to give you an idea about how you can use ‘if and else’ logic where youreally need it However, this example is too simple It can be complex when relational operators getadded and the logic may become complex
Finally, before leaving this section, I would like to show you another code snippet where the existingset of rules or principles has been changed
1 //code 4.3
2 main(List< String > arguments) {
3 bool firstButtonTouch = true ;
4 var firstButtonUntouch;
5 bool secondButtonTouch = false ;
6 bool thirdButtonTouch = true ;
7 bool fourthButtonTouch = false ;
18 else if((secondButtonTouch == true && thirdButtonTouch == true ) || fourthButtonTouch\
19 == false ) print ( "The giant stops." );
20 else if (thirdButtonTouch) print ( "You have not touched the second button." );
21 else if (secondButtonTouch) print ( "Touch any button to start the game." );
22 else if(thirdButtonTouch) print ( "The giant goes to sleep." );
23 else if (firstButtonUntouch) print ( "You have not touched any button." );
Trang 2224 if(fourthButtonTouch) print ( "The giant wakes up." );
25 else print("You have not touched any button." );
26 }
27
28 //output of code
29 The giant is sleeping.
30 You have not touched any button.
31 You can change the pattern and see what happens.
Conditional Expression
Consider this code where we check only one condition :
1 //condition? exp1 : exp2;
2 int num1 = 20;
3 int num2 = 30;
4 int smallerNumber = num1 < num2? num1 : num2;
5 // it is expected that num1 will always be smaller
6 int smallNumber = num1 ?? "Default number $num2";
7
8 TIPS: For small operations, we can use this conditional expression; it is extremely \
9 handy and useful. When we know the output, we can go for the second one. When there \
10 are two numbers, we can go for the first one.
Looking at Looping
For loop is necessary for iterating any collections of data, with the standard ‘for’ loop Here is atypical example of ‘for’ loop
1 //code 4.4
2 main(List< String > arguments) {
3 var proverb = StringBuffer( 'As Dark as a Dungeon.' );
Trang 2311 var userCollection = { "name" : "John Smith" , 'Email' : 'john@sanjib.site' };
12 myProducts.forEach((x, y) => print ( "${x} : ${y}" ));
Trang 2422 name: John Smith
23 Email: john @ sanjib.site
When we do not know the current iteration counter, the ‘forEach()’ method is a good option In usualcases, Iterable classes, such as, List and Set also support the ‘for()’ loop form of iteration Considerthis code:
While and Do-While
Be careful about handling the while loop Since a while loop evaluates the condition before the loop,you must know to stop the loop at right time before it enters into infinity
This is the pretty basic concept, but people often get confused about it
Trang 25In the above code, before the loop begins, the while() loop evaluates the condition Since the value
of the variable ‘num’ is 5 and it is greater than or equal to 1, the condition is true So the loop begins
As the loop begins, we have also kept reducing the value of the variable ‘num’; otherwise, it wouldhave been entered an infinite loop
The value of the variable reduces this way:
8 print ( "The value of the variable 'num' is decreasing to : ${num}" );
9 print ( "The factorial is ${factorial}" );
Trang 26Understanding the Looping Patterns
I have met many students who feel confused about the ‘while’ loop People often do not know that
a ‘for’ loop can also turn into an infinite loop if it is not handled properly
Actually, the concept of ‘loop’ is the same for every loop;be it ‘for’, ‘while’ or ‘do-while’ There arethree things to remember:
3 3 3 according to the condition, increment or decrement.
Let us consider a code snippet:
Trang 27The steps are quite logical We could not have decremented the value It would have taken us to theinfinite loop Because in the ‘condition checking’ step, we will stop when the value of ‘i’ either lessthan or equal to 5.
If we had decremented the value of ‘i’, by writing ‘i–’, the condition checking would have neverstopped until our computer’s memory permits
Now we have done the same thing in ‘while’ loop Only the steps are a little bit different
Trang 28of ‘for’ loop After that, according to the condition, we have incremented the value of ‘i’ inside the
‘while loop’ Once the value of ‘i’ equals 5, it immediately stops
Now check the ‘do-while loop’ code We start with the counter variable And then we increment ordecrement the value
In the last stage we check the condition inside the ‘while loop’
You may ask which one is better Actually, it depends on the context In some situations, ‘for loop’
is enough In fact, in most cases, we can manage with the ‘for loop’ However, in some situations,
we have to use while loop In our Flutter application, we will face such situations At that point, wewill understand the actual mechanism of looping
For Loop Labels
In some situations, we use nested for loops Inside a ‘for loop’, we can run another ‘for loop’; inmany cases, it is essential In Dart, there is a concept called ‘Label’ We can handle the ‘outer loop’and the ‘inner loop’ separately
Let us see this code first:
1 void labelsLoop (){
2 outerloop: for(var x = 1; x <= 3; x++){
3 print ( "One cycle of outerloop with $x starts and the whole innerloop runs." );
4 innerloop: for(var y = 1; y <= 3; y++){
Trang 29If you look at the output, you can understand how it works: One cycle of the outer loop with 1 startsand the whole inner loop runs.
1 Since outer loop 1 and inner loop 1 both are 1 it gives no output.
2 One cycle of the outer loop ends with 1
3 One cycle of the outer loop with 2 starts and the whole inner loop runs.
4 1
5 2
6 3
7 One cycle of the outer loop ends with 2
8 One cycle of the outer loop with 3 starts and the whole inner loop runs.
9 1
10 2
11 3
12 One cycle of the outer loop ends with 3
As you see in the above code the counter variable, condition checking and the increment parts arethe same in both cases: the outer loop and the inner loop So when the outer loop starts with 1, theinner loop inside the outer loop also starts with 1 and it should have completed the whole cycle But
we have injected an ‘if clause’ and told the program that when the value of the outer loop and theinner loop both are 1, break the ‘inner loop’ We have used the ‘Label’: ‘outer loop’ and ‘inner loop’
to demarcate the loops For the ‘if clause’ that particular cycle of ‘inner loop’ could not complete thewhole cycle However, after that, it goes on as usual
The ‘Label’ is a very distinctive concept of Dart Although, we have seen the same concept in Java
Continue with For Loop
You have just seen how we have explicitly broken the inner loop and stopped one cycle of the innerloop So ‘break’ is a very important concept while using ‘for loop’ At the same breath, the ‘continue’keyword also plays a very key role in ‘for loop’ Let us consider this code snippet:
Trang 30Is Dart easy?
Yes, the Dart programming language is very yes
However, we should always be careful about the syntactical errors Missing a semicolon or a dollarsign before a variable could be a big game changer
Especially, when you are going to build a large scale mobile application on iOS or Android, be verycareful about these small mistakes
Syntax-wise Dart has similarities with C, C#, Python, Java and JavaScript
You have seen how we have used the “comments” in our code
Try to contribute as much comment as possible to clear your standpoint as a developer
It is necessary because when another person reads your code, she will understand it Moreover shewill visualize it as you have visualized your code while writing
We will discuss comments at the right time
We have started our code with the top level function “main()”
It is required and special in nature because here the application executes
So inside the main() function we have called a function “doSomething()” which has a nested-functioninside it “lifeIsShort()”
Each function gives a display output with the function “print()” It is a handy way to display anyoutput Consequently, we have covered many things in our first program
Variable in Dart
In Dart everything is an Object Therefore a variable in Dart stores references to an Object
Let us create a variable and initialise
1 var name = 'Mutudu' ;
As the variables store references, in the above example the same thing happens
The variable called “name” contains a reference to a “String” object with a value of “Mutudu”.Every Object in Dart has a “type” In the above code, the “type” of the “name” variable is inferred to
be a “String”
Why?
Because we have not specified it, or mentioned it
On the contrary, we could have specified the “type”
Trang 311 String name = 'Mutudu';
There is another possibility An Object may not be restricted to any particular “type”
In that case, we can initialise it like the following way
1 Object name = 'Mutudu';
With reference to the above discussion, we have learned a few important facts about a variable
In Dart, a variable is always associated with a “type” We can either specify the “type”, or we canallow the variable to infer it
Like any other programming language, the Dart has many types We will discuss built in types inthe coming section
So far we have seen only one “Type” The String
However, there are other types also The integer, the boolean and a few others
We have also learned that the Dart allows us to be strongly-typed And at the same time we can beduck-typed
The phrase “strongly-typed” means we specify the “type” When we do not specify the “type”, it isknown as the “duck-typed”
If we don’t want to be specific about the “type”, we can use keywords like “var”, “Object”, or
“dynamic”
To understand the mechanism behind storing reference is simple
Whenever we declare and initialise a variable, a spot on the memory is booked
And in that spot the object is stored And the variable always refers to that spot
Since the name is “variable”, this reference can change
However, a question remains Suppose we do not initialise the variable
1 var name;
In that case, does this variable store any reference? Does it contain any value?
In the next section we will discuss that
What is null safety in Dart
Dart and Flutter, both, practice the “null-safety” A variable must have a value
Trang 32The word “NULL” in computer means “no value” It also means “undefined”, “uninitialized” or
“empty” value The word “NULL” neither means 0 Nor, it means a blank String Null safety inDart means, by default, the “type” in Dart code is not NULL Each “type” must have a well-definedvalue
What does that mean? When we declare a “type” for a variable, the variable must have a value
However, a variable might have a null value Although we have declared a “type” for that variable
In that case, the Dart ensures that we have assigned a correct value for that variable Otherwise, itwill throw an error
Suppose we have written the following code
The Dart and Flutter, both, practice the “null-safety” That is why it throws an error
But, we can avoid such error If we add a “?” sign after the declared “type”
Consider a code snippet like the following
Trang 331 void main(List<String> args) {
Before Dart 2.13, suppose we created the Dart Application the following way
1 dart create -t console-full my_application
In such case, we need to migrate to the “NULL-SAFETY”
1 cd my_application
2 dart migrate apply-changes
For example, run the following code in your console and watch the output
Trang 3411 String ? _aTextThatCouldBeNullButNot() => 'Not Null' ;
12 String ? notNull = _aTextThatCouldBeNullButNot();
13 print (notNull);
14 final aStudent = Student();
15 final aSchool = School();
16 aStudent.school = aSchool;
17 aSchool.student = aStudent;
18 print ( 'A student gets a school ' + aStudent.school.name);
19 print ( 'A school gets a student ' + aSchool.student.name);
5 A student gets a school L'cole
6 A school gets a student A Student
For full code snippet please visit the GitHub repository
What is Null Safety in Flutter
We always explicitly tell the Dart, or tell the Flutter that a variable is “NULL”
In the previous section we have discussed the “Null-Safety” in the Dart programming language Wehave learned the basic concept of the “Null-Safety” The same rule on the “Sound-Null-Safety” works
in Flutter However, in a different way
Firstly, let us check what is meant by the term “Sound-Null-Safety”?
From the Dart 2.12 and the Flutter 2, this principle of the Sound-Null-Safety becomes mandatory
Trang 35What does this principle say?
Every “type” in the Dart, and in the Flutter, is the “non-nullable” In other words, we explicitly tellthe Dart, or tell the Flutter that a variable is “NULL” Otherwise we must use a “?” sign after thedeclared “type”
1 int? x;
What does the above code convey?
It says, if we do not supply any integer value the value of the variable x would be the “null”
We have already learned in the previous section that a “NULL” value means a “undefined”,
“uninitialized” or “empty” value In other word, it is a “no value”
But can we build a Mobile Application with the “No-Value”? Or, with a “Null”?
We know that it is not possible
Therefore the Dart and the Flutter follows the “Sound-Null-Safety” design principle
It optimizes the compiler The application runs faster Moreover, if we place the “Null-Check” inright place, the application does not crash suddenly In addition, it does not throw any error.There are more
Let us a consider a simple Flutter Application In this application we consistently provide a “NULL”value
However, we cannot supply a Null value where the “type” String is necessary
In that case, we need to check it first If it is NULL, then an alternative String value is provided.Let us see the code now
9 class MyApp extends StatelessWidget {
10 const MyApp({Key ? key, required this.title}) : super (key: key);
11
12 final String ? title;
13
14 @override
Trang 3615 Widget build(BuildContext context) {
16 return const MaterialApp(
17 title: 'It can\'t be NULL' ,
18 home: MyHomePage(title: null),
43 title != null ? 'It\'s not NULL value' : 'It\'s a NULL value' ,
Trang 371 runApp(const MyApp(
3 ));
But, in the end, we have to check
1 title != null ? 'It\'s not NULL value' : 'It\'s a NULL value',
As we pass the “NULL” value to the “title” parameter We need to pass it through the Constructor
1 const MyApp({Key ? key, required this.title}) : super(key: key);
What is “type” in Dart and Flutter
The “type” plays an Important role in Dart and Flutter We must work using the correct “type”
As a beginner we need to understand what is “type” in the Dart and in the Flutter In this section,
we will also learn what are the “built-in-type” that the Dart provides
We have already learned what a “variable” is Now, any variable can hold different “type” of Data.The data could be an integer Or, it could be a String Or, a Boolean
To begin with we can declare the “type” before a “variable” To do that we need to specify the “type”
Is it an integer?
Then we will write like this:
1 int? x;
Why we have used a “?” sign? The reason has been explained before
It means, this variable could have a “NULL” value
At the same time, we could have written like this:
Trang 38When we do not specify the type, the Dart and the Flutter applies runtime checks.
Since it is optional, the Dart and the Flutter uses type inference
If you have interest t learn more, see the language tour
Declaring type is good, because if we do not supply proper type, the Dart static analyzer warns us.The bugs are caught in the compile time As a result, we can correct the bugs earlier
Consider the code below:
1 void printAListOfInteger(List<int> a) => print(a);
In the above code, we have declared a list of integers Therefore, before a variable like “list”, we need
to specify the particular “type”
The output is:
1 � Running with sound null safety �
2 Connecting to VM Service at ws://127.0.0.1:33047/ToG8jrELdFw=/ws
3 [1, 2]
We could have written the code in the following way also
Trang 391 // Both the code below will work fine
In the above code we have not specified the “type” of the variable However, when we assign a value,
we mention the “type”
Therefore, we can do the both Either, we can specify the “type” on the left hand side Or, we canuse the “type” on the right hand side
But, we need to maintain the right “type” always
Built-in Types in Dart
Type does not mean only “non-nullable” value
That is why, we do not write “Object” We write “Object?”
The “NULL” or “no-value” is also another “type” in Dart
The Dart language has special support for the following types
Trang 401 Numbers (int, double)
9 The value null (Null)
As we progress, we will check each type
When we assign a correct “type” to a declared variable, it is called a “literal”
1 String aText = 'A String';
In the above code, ‘A String’ is a String literal
Some other types also have special roles in the Dart language:
1 Object: The superclass of all Dart classes except Null.
2 Future and Stream: Used in asynchrony support.
3 Iterable: Used in for-in loops and in synchronous generator functions.
4 Never: Indicates that an expression can never successfully finish evaluating Mo\
5 st often used for functions that always throw an exception.
6 dynamic: Indicates that you want to disable static checking Usually you should \
7 use Object or Object? instead.
8 void: Indicates that a value is never used Often used as a return type.
We initialise an object of any of these special types using a literal
For example, “Hello John Smith” is a string literal And, “false” is a boolean literal
Consider this code: