1. Introduction
This series is written to help those who know the Kotlin or Java language quickly learn the Dart language to code Flutter. If you haven’t read part 1, you can read again part 1 here
2. Operators
Most of them are like Kotlin. However, there are a few other points, I have redlined and commented in the code.
In addition to the above operators:
- The function call operator is the same as Kotlin
()
. Example:print(3)
- The operator that calls the object’s member function or property is also
.
. For example:student.goToSchool()
orstudent.age
- In Dart there is only
as
, notas?
like Kotlin. - The
*
operator is also useful in case you need to generate a string of desired length.print('a' * 3); // Output là: aaa
3. If else
Just like Kotlin
1 2 3 4 5 6 7 8 9 | if (3 > 2) { print('Đúng'); print('Vào if') } else if (4 > 5) { print('Vào else if'); } else { print('Vào else'); } |
Or in the case in the { }
block there is only one statement:
1 2 | if (3 > 2) print('Đúng'); |
4. For loop
Kotlin seems to be easier to remember syntax. And Dart is a bit hard to remember, right? But don’t worry, because in part 2 I will introduce lambda expressions (lambda expressions), much easier to use than this. The variable list
in the image is faulty because I have not declared that list
variable. Through part 2, I will introduce the List
type as well.
5. While loop
Similar to Kotlin:
while
1 2 3 4 | while (!isDone()) { doSomething(); } |
do-while
1 2 3 4 | do { printLine(); } while (!atEndOfPage()); |
6. Break and continue
The use of break
and continue
same as Kotlin.
7. Switch and case
It is when
in Kotlin
8. String template, String raw
The String template is identical to Kotlin. It also uses $a
and ${a.func}
1 2 3 4 5 | void main() { var a = 3; print('Giá trị của a là $a Kiểu của a là ${a.runtimeType}'); } |
String raw is different from Kotlin, Kotlin uses """ """
tripple quote, and Dart uses double quote " "
.
1 2 | print("Can't help falling in love with Dart"); |
Notice, I didn’t use escape before the
'
character. That is, if you print the above sentence using single quotes, it must look like this:
1 2 | print('Can't help falling in love with Dart'); |
9. Exceptions
Like Kotlin, all Exceptions in Dart are unchecked exceptions, meaning you won’t be forced to try catch catch any line of code.
Dart provides two classes, Exception
(which is the parent class of all exceptions) and class Error
. Exception
and Error
no one inherits anyone. These 2 guys are completely different in nature. If Exception
are unforeseen exceptions and should try/catch
these in case of unwanted cases. If your app encounters an Error
, it proves that your code has failed, the code is bad, the code is error and you must fix it, not try/catch
.
The way to throw an Exception is the same as that of Kotlin:
1 2 | throw FormatException('Expected at least 1 section'); |
In addition, you can throw an exception regardless of the class:
1 2 | throw 'Expected at least 1 section'; |
10. try / catch / finally
Relatively similar to Kotlin, there are only 2 differences:
- How to catch a specific exception:
on FormatException catch (e) { }
- To throw an exception back, Dart gives us the keyword
rethrow
11. Null type
Class Null
is very special, it has only one instance which is null
. That’s why comparing nulls in Dart will have two types like this.
1 2 | if (a is Null) // tuy nhiên cách viết này bị warning |
or
1 2 | if (a == null) // cách viết này chuẩn |
When declaring a variable that has no initial value, the variable will be of type Null
, that’s why in lesson 1 I said that if there is no initial value, all variables have a default value of null
1 2 3 4 5 6 | void main() { var a; print('Giá trị của a = $a'); print('Type của a là ${a.runtimeType}'); } |
Output:
1 2 3 | Giá trị của a = null Type của a là Null |
12.The 3-star prince
Just like Java. This operator does not have Kotlin.
1 2 | var visibility = isPublic ? 1 : 0; |
Explanation: If variable isPublic == null
then variable visibility
is assigned the value 1
, otherwise it is assigned 0
13. The null-aware operator
Operator ??
1 2 3 4 5 | void main() { var x; // biến x đang là null print(x ?? 'x là null thì in vế sau ra'); } |
Output:
1 2 | x là null thì in vế sau ra |
This operator is similar to the Elvis ?:
Operator in Kotlin. That means if x
is null
then print the backside
Operator ?? =
1 2 3 4 5 6 | void main() { var x; // biến x đang là null x ??= 'Nếu x bằng null thì gán x bằng String này'; print(x); } |
Output:
1 2 | Nếu x bằng null thì gán x bằng String này |
If the variable x
is null
, assign the value by the back side to x
Operator ?.
?.
Used to check null before calling a function or property like Kotlin. For example student?.goToSchool()
or student?.age
.
14. List and Array Types
In Dart it combines the Array vs List type together with a type called List
. The syntax for creating a List
is [value, value, value, ...]
1 2 3 4 5 6 7 8 9 10 11 | void main() { // không sử dụng generic var list = [1, 'a', true]; // sử dụng generic var intList = <int>[1, 2, 3]; // một list object có kiểu int <=> listOf<Int>(1, 2, 3) trong Kotlin var numList = <num>[1, 2, 3.333]; // một list object kiểu num var dynamicList = <dynamic>[1, 'a', true]; // một list object có type bất kỳ } |
The add, set, remove, and get functions
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | void main() { var intList = <int>[1, 2, 3]; // một list object có kiểu int // add phần tử intList.add(4); // update phần tử tại index intList[0] = 5; // remove phần tử tại index intList.removeAt(0); // get phần tử tại index var b = intList[0]; } |
Collection if, collection for
This collection if is not supported by Kotlin.
1 2 3 4 5 6 7 | var nav = [ 'Home', 'Furniture', 'Plants', if (isMine) 'Outlet' ]; // chỉ khi biến isMine == true thì 'Outlet' mới được add vào list và ngược lại |
This collection for Kotlin also has no support.
1 2 3 4 5 6 7 | var listOfInts = [1, 2, 3]; var listOfStrings = [ 'số 0', for (var i in listOfInts) 'số $i' ]; print(listOfStrings); |
Output:
1 2 | [số 0, số 1, số 2, số 3] |
It listOfStrings
all elements in list listOfInts
and then listOfStrings
to listOfStrings
list
The spread operator (spread operator and null-aware spread operator)
This spread ...
operator Kotlin does not have, it helps me addAll a list B to a list A quickly.
1 2 3 4 | var listA = [1, 2, 3]; var listB = [0, ...listA]; // addAll tất cả phần tử của listA vào listB print(listB); // in ra: [0, 1, 2, 3] |
Similar to null-aware spread operator ...?
the same is true but differs in that it will check null before addAll.
1 2 3 4 | var listA; // listA đang null var listB = [0, 1, ...?listA]; // nên listA sẽ không được addAll vào listB print(listB); // in ra: [0, 1] |
15. Immutable and Mutable List
Actually, in Dart there is no concept of Immutable List. It just has a type called List
, which allows this type of add
, set
and remove
elements from the list, it is a mutable type. However, there are also 3 ways to circumvent the law to create an immutable list: v
Method 1 : Use List.unmodifiable
pass a variable of type List
1 2 3 | var a = List.unmodifiable(<int>[1, 2]); a.add(3); |
If immutable list Kotlin it will error compile right line of code a.add(3)
and of course you will not be able to run the program, then at Dart is a little different, it doesn’t report compile error but when run it will error at Runtime:
1 2 | Unsupported operation: Cannot add to an unmodifiable list |
In addition to the add function, the set, remove function will also have an exception:
1 2 3 4 5 | var a = List.unmodifiable(<int>[1, 2]); a.add(3); // throw Exception a[0] = 1; // throw Exception a.removeAt(0); // throw Exception |
Method 2 and 3 : use keyword const
1 2 3 4 5 6 7 8 9 10 11 12 | // Cách 2 var a = const [1, 2, 3]; a.add(4); // throw Exception a[1] = 1; // throw Exception a.removeAt(0); // throw Exception // Cách 3 const b = [1, 2, 3]; b.add(4); // throw Exception b[1] = 1; // throw Exception b.removeAt(0); // throw Exception |
16. Set
Set contains non-duplicate elements. The syntax for creating a Set
is {value, value, value, ...}
1 2 3 4 5 6 7 8 9 | void main() { // không sử dụng generic var set = {1, 'a', true}; // sử dụng generic var intSet = <int>{1, 2, 3, 2, 3, 4}; // <=> setOf<Int>(1, 2, 3, 2, 3, 4) trong Kotlin print(intSet); // in ra: {1, 2, 3, 4} } |
Set also support spread operator ...
and the null-aware spread operator ...?
17. Map
The syntax for creating a Map
is: {key: value, key: value, key: value, ....}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | void main() { // không sử dụng generic var map = {1: 3, 'a': 3.3, 0.333: true}; // sử dụng generic var genericMap = <int, dynamic>{1: 3, 2: 3.3, 3: true}; print(genericMap); // in ra: {1: 3, 2: 3.3, 3: true} // Hàm put genericMap[5] = 'abc'; // Hàm get var b = genericMap[5]; print(b); // in ra: abc } |
Note : Since both Set
and Map
use { }
so when we write code like this it will infer the type of Map
:
1 2 | var names = {}; // Tạo ra một Map rỗng, ko phải Set |
If we want to create an empty Set we can do the following:
1 2 3 4 | var names = <String>{}; // hoặc Set<String> otherNames = {}; |
Conclude
So we have come more than half the way. Hope you guys continue to watch the sequels
Reference: https://dart.dev/guides
Read on to Part 3: Quickly Learn Dart (Flutter) with Kotlin (Part 3)