So you heard about the Flutter framework and want to know what is it really about. But before that you need to know Dart programming language. Now the language itself is easy to learn and very similar to JavaScript(no pun intended). But there are some new aspects to the language that might surprise you and which must know to comfortably write Flutter code. Google has provided a fairly lengthy guide to get started with Dart which you can find here. I highly recommend you to read it. In these tutorial series I will teach you just enough Dart that you need to know to write Flutter applications with any pain.
Note: This is by no means an in depth tutorial on Dart, we are not covering all the features in the language. You will learn all the essential parts of the language that will be sufficient enough so that you don’t face any barrier from the language side when reading/writing Flutter code.
Hello World
Respect the holly ‘Hello World’ program.
1 2 3 |
main(List<String> args) { print('Hello World'); } |
Similar to Java every Dart program must have a main which is its entry point.
To run the program save it in a file named ‘hello_world.dart’ and execute the following command in terminal.
1 |
dart hello_world.dart |
Defining Variables
Just like in JavaScript you can use the var keyword to define variables.
1 2 3 4 5 6 |
main(List<String> args) { var number = 42; var name = 'Gurleen Sethi'; var salary = 150300.56; var isDoorOpen = true; } |
But! unlike JavaScript, in Dart 2, once assigned a type is assigned you can’t reassign a value with new type to the variable. Dart automatically infers the type of data from the right hand side.
You can also define variables by explicitly providing type of data.
1 2 3 4 5 6 |
main(List<String> args) { int number = 42; String name = 'Gurleen Sethi'; double salary = 150300.56; bool isDoorOpen = true; } |
If you don’t intend to change the value held by a variable, then declare it with a final or a const.
1 2 3 4 5 6 7 8 |
main(List<String> args) { final int number = 42; const String name = 'Gurleen Sethi'; //Omit explicitly defining data types final salary = 150300.56; const isDoorOpen = true; } |
Difference between final and const is that const variables are compile time constants i.e. const variables must have a value during compile time, for example const PI = 3.14; , whereas variables that are final can only be assigned once, they need not be assigned during compile time and can be assigned during runtime.
Built In Data Types
Dart provides all the basic data types that you can expect from a modern language.
- Numbers
- Strings
- Booleans
- Lists
- Maps
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
main(List<String> args) { //Numbers int x = 100; double y = 1.1; int z = int.parse('10'); double d = double.parse('44.4'); //Strings String s = 'This is a string'; String backslash = 'I can\'t speak'; //String interpolation String interpolated = 'Value of x is $x'; //Prints: Value of x is 100 String interpolated2 = 'Value of s is ${s.toLowerCase()}'; //Prints: Value of s is this is a string //Booleans bool isDoorOpen = false; } |
Lists
Declaring a list is very simple, use can simple use square brackets [ ] to define a list. Below are some common operations on a list.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
main(List<String> args) { var list = [1,2,3,4]; print(list); //Output: [1, 2, 3, 4] //Length print(list.length); //Selecting single value print(list[1]); //Outout: 2 //Adding a value list.add(10); //Removing a single isntance of value list.remove(3); //Remove at a particular position list.removeAt(0); } |
If you want to define a List that is compile time constant i.e. the content of lists are unchangeable then use the const keyword.
1 2 3 |
main(List<String> args) { var list = const [1,2,3,4]; //Cannot alter elements of this list } |
Maps
Defining maps is equally straight forward. Use the curly brackets { } to define a map.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
main(List<String> args) { var map = { 'key1': 'value1', 'key2': 'value2', 'key3': 'value3' }; //Fetching the values print(map['key1']); //Output: value1 print(map['test']); //Output: null //Add a new value map['key4'] = 'value4'; //Length print(map.length); //Check if a key is present map.containsKey('value1'); //Get entries and values var entries = map.entries; var values = map.values; } |
You can also define a map using the Map constructor.
1 2 3 4 |
main(List<String> args) { var squares = new Map(); squares[4] = 16; } |
If you want to define a Map that is compile time constant i.e. the content of map are unchangeable then use the const keyword.
1 2 3 4 5 6 7 8 |
main(List<String> args) { var squares = const { //Cannot change the content of this map 2: 4, 3: 9, 4: 16, 5: 25 }; } |
Functions
Functions in Dart are as simple as it can get, somewhat similar to javascript. All you need to do is provide a name, a return type and parameters.
1 2 3 4 5 6 7 8 |
main(List<String> args) { var name = fullName('John', 'Doe'); print(name); } String fullName(String firstName, String lastName) { return "$firstName $lastName"; } |
You can even omit the return type and the program will still work.
1 2 3 4 5 6 7 8 |
main(List<String> args) { var name = fullName('John', 'Doe'); print(name); } fullName(String firstName, String lastName) { return "$firstName $lastName"; } |
Here is short hand way of writing single line functions.
1 2 3 4 5 6 |
main(List<String> args) { var name = fullName('John', 'Doe'); print(name); } fullName(String firstName, String lastName) => "$firstName $lastName"; |
Named Parameters
Dart has something called named parameters, when using named parameters you will have to specify the name of parameter while calling the function. To enable named parameters just wrap the parameters in the function with curly brackets { }.
1 2 3 4 5 6 7 8 |
main(List<String> args) { var name = fullName(firstName: 'John', lastName: 'Doe'); print(name); } fullName({String firstName, String lastName}) { return "$firstName $lastName"; } |
If you don’t provide the name when calling a function with named parameter then the program will crash.
Default Parameter Values
You can give default values to the named parameters thus making them optional when calling the function. In the below example we have given lastName a default value.
1 2 3 4 5 6 7 8 |
main(List<String> args) { var name = fullName(firstName: 'John'); print(name); } fullName({String firstName, String lastName = "Lazy"}) { return "$firstName $lastName"; } |
Functions are First Class Objects
In Dart you have a lot of flexibility with functions, for example, you can pass a function inside another function.
1 2 3 4 5 6 7 8 9 10 11 |
main(List<String> args) { out(printOutLoud); } out(void inner(String message)) { inner('Message from inner function'); } printOutLoud(String message) { print(message.toUpperCase()); } |
Here I have defined a function named out that takes in a parameter a function(that has parameter message). Then I have defined a functions named printOutLoud, all it does is print a String in upper case.
Dart also has anonymous functions, so in above example rather than predefining a function(printOutLoud) we can pass an anonymous function.
1 2 3 4 5 6 7 8 9 |
main(List<String> args) { out((message) { print(message.toUpperCase()); }); } out(void inner(String message)) { inner('Message from inner function'); } |
Another example of anonymous function.
1 2 3 4 5 6 7 |
main(List<String> args) { var list = [1,2,3,4]; list.forEach((item) { print(item); }); } |
That is it for this tutorial, see you in the next one.
Next Tutorial >> Just enough Dart for Flutter – Tutorial 02 – Control Flow and Exceptions.
12 Comments
Gabriel · June 13, 2018 at 12:02 pm
Very helpful, thanks
Ewald · June 17, 2018 at 2:18 pm
Excellent! Thank you for a great introduction to Dart, I look forward to the rest of the tutorials.
Dustin · June 18, 2018 at 4:00 pm
> Dart automatically infers the type of data from the left hand side.
I think you mean right hand side.
Gurleen Sethi · June 18, 2018 at 6:51 pm
Thank You Dustin for the correction!
Michael Forde · December 2, 2018 at 8:07 pm
Thank you. Very useful.
Mahendra · February 8, 2019 at 8:32 pm
Hello Sir, very nice tutorial for a complete novice like me. All was ok till i came across anonymous function. I got clean bowled. Please explain the example. printOutLoud is called without any parameters. Is inner a function, if yes than how is it declared after out in curly braces. What is the sequence of compiler while executing out(printOutLoud)
main(List args) {
out(printOutLoud);
}
out(void inner(String message)) {
inner(‘Message from inner function’);
}
printOutLoud(String message) {
print(message.toUpperCase());
}
Gurleen Sethi · February 18, 2019 at 2:39 pm
It would print ‘Message from inner function’. You can run dart code in browser, just go to https://dartpad.dartlang.org.
ridham · June 28, 2019 at 4:34 am
how to take input from user in dart??
Just enough Dart for Flutter – Tutorial 02 – Control Flow and Exceptions - TheTechnoCafe · June 18, 2018 at 6:52 pm
[…] Previous Tutorial << Just enough Dart for Flutter – Tutorial 01 – Variables, Types… […]
Dart4Flutter-01– 變數, 型別和 函式 | 程式前沿 · June 22, 2018 at 4:34 pm
[…] http://thetechnocafe.com/just… […]
Flutter Crash Course - 1 - Installation and Overview - TheTechnoCafe · October 23, 2018 at 4:46 pm
[…] Flutter is hybrid mobile application from Google that lets you develop both Android and iOS application from a single codebase. It is not any regular hybrid framework. Unlike other frameworks, Flutter application compiles down to native platform code, resulting in performance and smoothness that has never been seen from a hybrid framework before. Flutter applications are written in Dart language. Dart is a modern, easy to learn Object Oriented language with simple and clean syntax. Dart is very easy language, if you know Java/Javascript you will breeze through Dart code without any problems. Still if you want to learn Dart before getting stated, I have written a tutorial series Just enough Dart for Flutter. […]
Dart Extension Members - TheTechnoCafe · November 6, 2019 at 12:14 am
[…] Just Enough Dart for Flutter – Tutorial Series […]