- HelloWorld
- การเรียกใช้ฟังก์ชัน
- การ print ตัวแปร และ expression
- การประกาศตัวแปร
- Default value และการใช้ assert()
- Final และ const
1. HelloWorld
1 2 3 |
void main() { print("Hello World!"); } |
จะได้
1 |
Hello World! |
 
2. การเรียกใช้ฟังก์ชัน
1 2 3 4 5 6 7 8 9 10 |
// Define a function. printInteger(int aNumber) { print('The number is $aNumber.'); // Print to console. } // This is where the app starts executing. main() { var number = 42; // Declare and initialize a variable. printInteger(number); // Call a function. } |
บรรทัดที่ 8 : var
เป็นการกำหนดตัวแปรโดยไม่ระบุชนิด
จะได้
1 |
The number is 42. |
 
3. การ print ตัวแปร และ expression
$variableName
${expression}
1 2 3 4 5 6 7 8 9 10 11 |
void printNumber(int number1, int number2) { print("Number1 is $number1"); print("Number2 is $number2"); print("Sum = ${number1 + number2}"); } main() { int number1 = 20; int number2 = 40; printNumber(number1, number2); } |
จะได้
1 2 3 |
Number1 is 20 Number2 is 40 Sum = 60 |
 
4. การประกาศตัวแปร
1 2 3 4 5 6 7 8 9 10 11 |
main() { var name1 = "Jack1"; dynamic name2 = "Jack2"; Object name3 = "Jack3"; String name4 = "Jack4"; print('name1 = $name1'); print('name2 = $name2'); print('name3 = $name3'); print('name4 = $name4'); } |
บรรทัดที่ 2-4 : ประกาศตัวแปรแบบไม่ระบุชนิด แต่ทางที่ดีใช้ var
ตาม style guide recommendation
จะได้
1 2 3 4 |
name1 = Jack1 name2 = Jack2 name3 = Jack3 name4 = Jack4 |
 
5. Default value และการใช้ assert()
assert() ใช้ตอน development เท่านั้น ห้ามใช้ตอน production
1 2 3 4 5 6 7 |
main() { int x; assert(x == null); int y = 10; assert(y == null); } |
บรรทัดที่ 2 : ค่า default ของตัวแปรคือ null
บรรทัดที่ 3 : assert()
ใช้ตรวจสอบเงื่อนไข บรรทัดนี้จริงก็ไม่มีอะไรเกิดขึ้น
บรรทัดที่ 6 : assert()
ในบรรทัดนี้ไม่จริง ก็จะแจ้ง error ออกมา
จะได้
1 2 3 4 5 6 7 |
Unhandled exception: 'file:///D:/Project/dart/my_dart/bin/my_dart.dart': Failed assertion: line 6 pos 10: 'y == null': is not true. #0 _AssertionError._doThrowNew (dart:core/runtime/liberrors_patch.dart:40:39) #1 _AssertionError._throwNew (dart:core/runtime/liberrors_patch.dart:36:5) #2 main (file:///D:/Project/dart/my_dart/bin/my_dart.dart:6:10) #3 _startIsolate.<anonymous closure> (dart:isolate/runtime/libisolate_patch.dart:289:19) #4 _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12) |
 
6. Final และ const
ประกาศแบบบรรทัดที่ 9 แล้วจะแก้ไขค่าทีหลังไม่ได้
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
final name = 'Bob'; // Without a type annotation final String nickname = 'Bobby'; const bar = 1000000; // Unit of pressure (dynes/cm2) const double atm = 1.01325 * bar; // Standard atmosphere var foo = const []; final bar2 = const []; const baz = []; // Equivalent to `const []` main() { foo = [1, 2, 3]; // Was const [] baz = [42]; // error } |
จะได้
1 2 3 |
bin/my_dart.dart:13:3: Error: Setter not found: 'baz'. baz = [42]; // error ^^^ |
Link