Afrikaans
Akan
Albanian
Amharic
Arabic
Armenian
Azerbaijani
Basque
Belarusian
Bemba
Bengali
Bihari
Bosnian
Breton
Bulgarian
Cambodian
Catalan
Cebuano
Cherokee
Chichewa
Chinese (Simplified)
Chinese (Traditional)
Corsican
Croatian
Czech
Danish
Dutch
English
Esperanto
Estonian
Ewe
Faroese
Filipino
Finnish
Frisian
Ga
Galician
Georgian
German
Greek
Guarani
Gujarati
Haitian Creole
Hausa
Hawaiian
Hebrew
Hindi
Hmong
Hungarian
Icelandic
Igbo
Indonesian
Interlingua
Irish
Italian
Japanese
Javanese
Kannada
Kazakh
Kinyarwanda
Kirundi
Kongo
Korean
Krio (Sierra Leone)
Kurdish
Kurdish (Soranî)
Kyrgyz
Laothian
Latin
Latvian
Lingala
Lithuanian
Lozi
Luganda
Luo
Luxembourgish
Macedonian
Malagasy
Malay
Malayalam
Maltese
Maori
Marathi
Mauritian Creole
Moldavian
Mongolian
Myanmar (Burmese)
Montenegrin
Nepali
Nigerian Pidgin
Northern Sotho
Norwegian
Norwegian (Nynorsk)
Occitan
Oriya
Oromo
Pashto
Persian
Polish
Portuguese (Brazil)
Portuguese (Portugal)
Punjabi
Quechua
Romanian
Romansh
Runyakitara
Russian
Samoan
Scots Gaelic
Serbian
Serbo-Croatian
Sesotho
Setswana
Seychellois Creole
Shona
Sindhi
Sinhalese
Slovak
Slovenian
Somali
Spanish
Spanish (Latin American)
Sundanese
Swahili
Swedish
Tajik
Tamil
Tatar
Telugu
Thai
Tigrinya
Tonga
Tshiluba
Tumbuka
Turkish
Turkmen
Twi
Uighur
Ukrainian
Urdu
Uzbek
Vietnamese
Welsh
Wolof
Xhosa
Yiddish
Yoruba
Zulu
0 Now in the last lesson we implemented the geolocator package to be able to fetch our current location 1
both for Android and iOS. 2
And the code is super simple. 3
It's basically a single line that fetches us the current location of the phone depending on which location 4
accuracy we want. 5
However there are two key words that we're using in this code that comes from the documentation for 6
the package that we've never really seen before. 7
So in order to understand this, we have to first learn about asynchronous programming and why it's useful. 8
Now when we're writing code, there are lines of code which take a very short amount of time to execute. 9
For example if we wanted to run a print statement, it's a single line statement prints the word hello 10
world into the console. 11
And this takes fractions of a second to complete. 12
But sometimes there are things that might take more time. 13
For example if we wanted to load a large image from the Internet. Even if we're doing it in a browser 14
and if your internet is slightly slower, you might see this painful loading of the image where it takes 15
absolutely forever. 16
And this is because there's a lot of data that we're trying to transfer through cables under the sea 17
literally trying to get data. And the larger the amount of data the longer the time it takes for it to 18
load. Now 19
consider if we made this function. It's a function that returns nothing. So it returns void but, it has a 20
body that is composed of three steps or three things that it tries to do. 21
And the first thing is to simply print 'Hello moon' to the console. 22
This is pretty quick to execute. 23
So we see the result pretty much immediately. 24
Now the next thing is to load an image from NASA of the moon. And I don't know how often you've 25
done this but they're huge and that can take a long time. 26
But because our function goes from top to bottom, our third Step can't execute until the second step 27
is done. 28
So it's only once this image is loaded that the computer will actually run the very last statement, which 29
is to print the word 'Hello Jupiter' into the console. 30
Now this behavior is what we would call synchronous. 31
Everything happens in synchrony. 32
Step 1 happens, then step 2 happens and only when step 2 has concluded or has finished and we've 33
gotten the image back does step 3 actually execute. 34
Now what would it look like if this was asynchronous? 35
Well step 1 would execute as usual no changes there. But step 2, let's say that we're now loading 36
our image from NASA asynchronously. 37
Well in this case while the image is loading and we're trying to wait on that data to come back, we can 38
already execute step 3. And we don't have to wait for this to finish before we continue in our code. 39
Now why is this actually useful? 40
I want you to imagine that come Monday you're going to work and your boss tells you to get me 100 passport 41
numbers. 42
Get them to me right now. 43
So you have to call up all of the customers one by one and ask them what is your passport number. 44
So you have this checklist and you're going from the top to the bottom one by one calling up each customer. 45
Now it's not so straightforward right? 46
Very few people remember their passport numbers off the top of their head. 47
So you have to start the call ask them for their phone number and then they have to rummage around their 48
house and to actually find their passport to be able to give you that passport number. 49
And this can take anywhere from a couple of seconds to a couple of minutes depending on how well they've 50
stashed away their passport. 51
So what are you doing while all of that is happening? Let's represent this process using a graph. On the 52
horizontal axis is time and we have a couple of units of time, you can imagine each square as a second. 53
Now let's say that it only takes you maybe a second to ask that customer, 'Hey can you give me your passport 54
number?' 55
So your job is kind of done now. 56
The next step is waiting for the user to look for their passport and give you that number. And all of 57
that time you're just sitting there twiddling their thumbs on hold on the call. And you're not really 58
being productive right now 59
right? 60
But once they've given you their passport number you can finally spring into action again and you can 61
go and call the next customer, and then the same process repeats on and on again until you've gotten 62
to the end of that list and you've reached 100 customers. And nobody likes being on hold waiting 63
on a call, 64
right? 65
And if that is the majority of your day then it's not going to feel great. 66
Now you might have realized that there's a different way of doing this. 67
You could in fact have just drafted individual e-mails, say you wanted to keep it personal to be able 68
to persuade your customers to give you the passport numbers, and you could have simply sent these e-mails 69
off to all of your customers one by one. Now afterwards 70
this leaves you free to do any other tasks that you need to do. 71
And as the replies come in, you can respond to them. So you no longer have to be there on the phone waiting 72
for their response. 73
Now if we were to represent this in the same graphical style, then your day might look more like this. 74
You send each customer an individual email but it doesn't really matter how long it takes them to respond 75
because you're able to continue onto the next task, 76
send the next e-mail or do the next thing and they can take their time finding their passport and only 77
once they have their passport number do they respond to you and you get that email response back. And 78
it's in that moment that you can actually act on it and you don't have to be on hold waiting for them 79
to fetch the information you need. So now your day looks more like this. 80
You're using every chunk of the day doing something productive and you're responding to the e-mails 81
that you've sent out as and when the responses come in. 82
So compare these two side by side where in one case you're doing something, waiting, doing something, waiting, 83
doing the next thing and waiting. 84
Well this is synchronous programming. Whereas in the other case you're basically initiating a task and 85
only once that task is complete 86
do you get notified and act on it. 87
So this means that we're able to use only five units of time instead of nine units of time to achieve 88
the same thing. 89
This is the difference between synchronous and asynchronous programming. 90
Now notice how this is all being done by one worker, you. It's not that you have 10 people trying to 91
get 100 passport numbers from 100 customers. It's actually still one person doing that 92
task but it's just done more efficiently because you're letting the customer take their time finding 93
those numbers and only getting your attention once they have the results. 94
So let's build out a real example and take a look at what it would look like if we were to write it 95
in code. Inside your clima project, you're going to right click and you're going to create a new Dart 96
file. And we're going to call this file simply just a scratch file. 97
So it's going to be scratch.dart and it's going to be created inside your main project right here. 98
Now inside this file, this is completely separate from our project, and it lets us test out some Dart 99
code. 100
But unlike DartPad, we're able to tap in to all of the available Flutter and Dart libraries. 101
Now if you head over to this link which will be in the course resources for this module, then you can 102
see that there's a little bit of code that I've already written as some starting code for you. 103
So go ahead and copy all of it and paste it into your scratch.dart. 104
So all that we have here are three functions, task 1, task 2 and task 3. And they're called in sequence 105
inside a function called performTasks. And then in the main function which is our entry point to this 106
particular file, we call performTasks. 107
So right now, you can run this scratch.dart without running any of the rest of our code by simply 108
right clicking on the file and clicking on run scratch.dart. And you should see your console pop up 109
and you can see that this is an isolated file that you can run without having to take all the time to 110
load up the UI and build it onto an app. 111
So this is where we're going to experiment with our Dart code. 112
And you can see that as expected, all that happens is we print T'ask 1 is complete', 'Task 2 is complete', 113
Task 3 is complete.' 114
But the important thing to notice is that they happen in sequence because inside our method perform 115
tasks we said to do 1 then 2 then 3, in this order. 116
These functions are getting called sequentially. 117
Now let's say that task 2 was actually a really time consuming task, like downloading a picture of the 118
moon off the NASA's website. 119
Well let's simulate something taking a long time. 120
We can create a new duration object called threeSeconds. 121
And this is going to be equal to a new duration object. 122
And here we can specify the amount of time 123
so microseconds, milliseconds, seconds, minutes, hours, days. 124
I don't want you guys have to watch this video for days to be to see this example. 125
So we're going to keep it short to maybe let's say a delay of three seconds 126
right? 127
So now to be able to enact this three second duration delay, we're going to use a function called sleep. 128
Now the important thing about sleep is that this is a synchronous operation. 129
So we will have to finish before the next line can be executed. 130
And it takes a single input which has a duration object and we can simply put our threeSeconds in here 131
as the amount of time that we want to pause for. 132
So when we call task 2, it will set a duration of three seconds and it will sleep our program for three 133
seconds. And then and only then, do we get to print 'Task 2 complete' into the console. And because task 134
3 comes after task 2, then theoretically it should also come after three seconds delay. 135
So now let's go ahead and click run again. 136
So notice scratch.dart is currently selected as the thing that we're going to run. 137
And now you can see that task 1 complete, 1 2 3, task 2 task three. So if you're watching this 138
video on double speed or half speed might be a good time to actually put it back to normal speed because 139
I'm going to try and show you what actually happens with these delays. 140
Let's just run that again and notice Task 1, 1 2 3, Task 2 Task 3. 141
So we know that each of these tasks printing a single string into the console basically takes a negligible 142
amount of time. All that's causing the delay is this artificial delay that I've put in here using the 143
sleep method which comes from dart:io. Now because there are a lot of cases where things can take an unpredictable 144
but usually a long period of time to complete such as downloading something or reading something from 145
a file or even doing complex computations, 146
it all takes a large amount of time. 147
And what we don't want to happen is for everything else, every subsequent task, to be held off until this 148
task is complete. 149
So what if we could say that, you know what? Let task 2 do its thing in the background but continue forward 150
and do the things that you can do right now. 151
And once that long task is completed well, then we'll deal with the results once that actually happens. 152
In this case we would be using an asynchronous method instead of a synchronous one. 153
So let's simulate a asynchronous delay. 154
We can do this by instead of using sleep, 155
we can use a method called Future.delayed. So it has two inputs, 156
one is a duration and the second is a computation to run after the delay. 157
This is what we need. 158
So the first input is going to be a three second delay and then I'm going to add a callback to specify 159
what should happen after those three seconds are up. And it's namely creating this result and printing 160
that task 2 is complete. 161
So I'm going to cut that and paste it into that. 162
Now the way that our code is going to run is this is a asynchronous method. And we know it's an asynchronous 163
method because it returns something called a future. 164
So whenever you see a future in the documentation, you'll know that the method is something that will 165
happen asynchronously. And it will delay by three seconds but it will allow other lines of the code to 166
run if they can. 167
Now once these three seconds are up, then it triggers the computation in the callback. 168
And in this case it's to create the result, task 2 data and the print task 2 complete. 169
Now if we run our code again, let's watch the console and see how it works this time. 170
Remember that at the top here where we say perform tasks, I haven't changed that order at all. 171
It's still task 1 should perform, then task 2 then task 3 gets called. 172
But now let's see what happens down here. 173
Task 1 task 3 completed almost immediately, and then task 2 complete after a three second delay. 174
So this is asynchronous programming in action. 175
We saw that because task 2 took a long time. 176
We were waiting for it to happen but we continued. We plowed ahead with the things that we can do right 177
now. 178
And once task 2 completed, it's then and only then, does it actually get executed and printed into the 179
console now. 180
That's all very well and good for things like downloading images from the Internet or doing time intensive 181
tasks. 182
But sometimes we need the results of the tasks to be able to continue to the next task. 183
So for example let's say that our task 3 actually required an input that comes from task 2. 184
So let's change task 3 to take a string input 185
that's called task2Data. And then let's use that inside 3, so task 3 complete with and then 186
we'll add all task 2 data inside this function. 187
Now task 3 relies on something that comes from task 2. 188
So that means we have to return something from task 2 to be able to do that. 189
So let's output a string from task 2 instead of nothing. 190
And we're going to output this result right here. 191
Let's create a new string up here 192
called result. 193
And let's set it to nothing to begin with, but only after our asynchronous method has delayed by 3 seconds. 194
So let's say we're fetching some data from the Internet. Only once that's completed 195
do we assign result to a value. 196
And finally at the very end do we actually return this result as the output of our task 2. 197
So now that task 2 has a output we can assign that to equal a new string called task2Result, going 198
to equal to the output of task 2. And then we're going to use that inside task 3. 199
So task 2 result is going to be the input for task 3. 200
So the entire order of things is task 2 will execute asynchronously so it can take as long as it wants 201
in the background. 202
Now once it's done though, it's going to assign some data to a string called result and then it's going 203
to print that it's completed and also output result. 204
Now at this stage, we're going to take that result and bind it to a new string and then use that as the 205
input for the next step which is inside task 3. 206
What do you think will happen given that we know that task 2 is asynchronous and it can complete at 207
any time at once and our code will actually skip ahead to try and do the things that it can't right 208
now? 209
So if we take a look at running our code, you can see that task 1 and task 3 complete almost immediately 210
and task two is taking its three second delay to complete. But because task 3 relies on some data 211
from task 2, 212
so if it executes immediately then it won't actually have the information to hand. 213
And so that's why we're getting task 3 complete with null 214
at this point because task2Data isn't available until the task 2 completes. 215
So how can we fix this? 216
Well we can make our code actually wait so we know that this is an asynchronous method and we allow 217
other code to continue on and not have to wait for this to finish. 218
But in this case because task 3 relies on this second task to complete, what we can do is we can make 219
our code wait for it to complete before we call the next task. To do this 220
we can change this into a async method. 221
So this is called a modifier and we add it just before the curly brace. 222
By adding that async keyword, we can now have access to the keyword 223
that's await. 224
And we're going to put it right in front of task 2. 225
So before we call task 2, we're going to wait for it to finish. Now inside task 2, we have to make 226
some changes too. Instead of returning a string, 227
we have to return something that's called a future. 228
Now a future is something that will exist in the future. 229
Right now it's nothing because our task hasn't completed. But once our task has completed then our future 230
will be an actual thing like an actual string or an actual integer. Now we have to also mark this method 231
as asynchronous to be able to say that we have to wait for this Future.delayed method to complete 232
before we can output our results. 233
So now with this updated code with our async and await where we're waiting on the parts that need to 234
complete in order to give an input to task 3, 235
now if I hit play and run my code, you can see task 1 complete happens first. And then task 2 happens 236
after a delay and then finally task 3 happens using the data that comes back after task 2 is complete. 237
Now we've talked a lot about futures 238
when we were writing our code in the demo. What exactly are futures? 239
Well they're kind of similar to receipts. 240
Let me explain what I mean. 241
Let's say that you go to the coffee shop and you order a cup of coffee. 242
Now at this point you'll get a receipt with an order number. And you can go away and do something else 243
or check Instagram or check Facebook while your coffee is made. 244
You don't want to stand there waiting for it to be done. 245
So then once the coffee is done, they'll shout for your order, 'Order number 1 please come and collect.' 246
And now you'll show up and you can actually claim your coffee based on your order receipt. That receipt 247
is the same as a future in Dart. 248
It's not the actual thing that you want. 249
It's just a promise that you will get something in the future. If you come from JavaScript and you've 250
heard of promises, then it's exactly the same. 251
It's something that doesn't exist right now but after it's completed its thing, after it's gotten the 252
image or after it's downloaded the text, then your future will actually materialize into a real object 253
like a real string or a real integer. 254
Now you can be more specific with your futures. 255
You can specify that this is going to be a future string or this is gonna be a future integer, and we 256
do that by using an angle bracket. 257
So in this case we can change our date type from just a generic dynamic future to something that is 258
a specific data type. 259
So it could be a future string. 260
So this means that we're expecting a future string 261
when we call this method task 2. And right now if I decide to comment out this line and try to print 262
what task 2 is equal to, then you can see that it's a instance of a future string. 263
It's not an actual string yet. It's only once task two is complete 264
does that future string materialize and change into an actual string. Now asynchronous programming is 265
not the easiest concept to grasp. But I hope through reviewing and re-reviewing this lesson and also 266
completing the modules that are ahead of you, where we're going to be using async and await and 267
futures in a lot more places, you're going to steadily get used to this idea of asynchronously doing 268
something. Instead of doing everything in sequence which is synchronous programming, 269
we're trying to be more efficient with our time or with the computer's time by trying to asynchronously 270
do our tasks so that things don't necessarily happen in the order that we programmed it to, but we end 271
up completing our tasks in the quickest way using the shortest route. 272
So this concept is going to come up again and again. 273
Don't worry if this hasn't completely settled in your mind yet. We're going to be reviewing this a lot 274
more in the future. But in the next lesson we're going to get back to making our app and getting our 275
location data as soon as we load up the screen. 276
So for all of that and more, I'll see you on the next lesson.
Can't find what you're looking for?
Get subtitles in any language from opensubtitles.com, and translate them here.