Cover image

Flutter EP.2 ภาษา Dart

28 May 2020

Share to:

สวัสดีครับ หลังจาก EP.1 เราได้เรียนรู้การ Install และสร้าง Project กันไปแล้ว ในบทความนี้ก็เป็น EP.2 แล้วนะครับ จะเป็นเรื่องเกี่ยวกับ ภาษา Dart ซึ่งเป็นเนื้อหาที่จําเป็นในการพัฒนา Mobile application ด้วย Flutter

Feature ของ Dart

  • ต้องระบุ type ให้ชัดเจน
  • รองรับ Compile ทั้ง 2 แบบ คือ AOT (Ahead of time) กับ JIT (Just In Time) JIT compilation ถูกใช้ตอน Development โดยการใช้ compiler ที่เร็วมาก และเมื่อจะ Release จะใช้การ compiled AOT
  • เป็นภาษาที่ง่าย และประสิทธิภาพดี
  • ถูกสนับสนุนโดย Google
  • เป็นพื้นฐานในการเขียน Flutter
  • ทำงานยากๆ ด้วย code น้อยๆ
  • ทํางานเร็วกว่า Javascript
  • มี Tools + IDE support เยอะ Webstorm, IntelliJ IDEA, and Android Studio, , VS Code, Sublime text, VIM, Emacs, Atom

เพื่อให้ง่ายในการเรียนรู้ และทดสอบ ผมจะแนะนํา Website dartpad.dev/ เป็น Website ที่ช่วยให้เราสามารถ Run code ภาษา Dart เพื่อทดสอบได้แบบ Online

Image

ภาษา Dart จะมี Syntax ของภาษาคล้ายกับภาษา JavaScript มากๆ ดังนั้นผมจึงไม่กล่าวถึง Syntax ทั้งหมด แต่จะดึงเอา Syntax ที่คิดว่าจําเป็นต้องใช้ หรือใช้บ่อยๆมาเรียบรู้กันครับ ดังนี้

Comments

// In-line comment

/*
Block comment
*/

/// Documentation

Data Type

Int - ข้อมูลประเภท Number เช่น 69

double - ข้อมูลประเภท Number (แบบมีทศนิยม) เช่น 69.88

bool - true/false

String - ข้อมูลประเภทตัวอักษร ‘Hello’ หรือ “Hello”

dynamic - เป็นข้อมูลได้ทุกประเภท

ตัวอย่างการใช้งาน

main() {
  int amount1 = 100;
  var amount2 = 200;
  print('Amount1: $amount1 | Amount2: $amount2 \n');

  double dAmount1 = 100.11;
  var dAmount2    = 200.22;
  print('dAmount1: $dAmount1 | dAmount2: $dAmount2 \n');

  bool isItTrue1 = true;
  var isItTrue2  = false;
  print('isItTrue1: $isItTrue1 | isItTrue2: $isItTrue2 \n');

  dynamic weakVariable = 100;
  print('WeakVariable 1: $weakVariable \n');

  weakVariable = 'Dart Programming';
  print('WeakVariable 2: $weakVariable');

  String name1 = 'Thiti';
  var name2    = 'Yamsung';
  print('My name is: $name1 $name2 \n');
}

เมื่อประกาศตัวแปรแล้ว จะไม่สามารถเปลี่ยนเป็นตัวแปรอื่นได้ ตัวอย่างเช่น

void main() {
  var name = 'Thiti'; // type this as String
  print(name);

  name = 800; // Will show error here
  print(name);
}

ถ้าประกาศตัวแปรเป็นแบบ Dynamic สามารถทำการเปลี่ยนประเภทตัวแปรทีหลังได้

void main() {
  var weakType; // dynamic ประกาศไม่ assign ค่า ตอนเริ่มต้น มี ค่าเท่ากับประกาศ dynamic

  weakType = 'Thiti';
  print(weakType);

  weakType = 100;
  print(weakType);
}

Function type

การประกาศ Function ได้ตามตัวอย่างด้านล่าง

กรณีที่เป็นประเภท Dynamic, Dart จะเลือกประเภทที่เหมาะสมให้

void main() {
  print(square(5));
  print(doubleSquare(5.5));

  print(dynamicSquare(5));
  print(dynamicSquare(5.5));
}

int square(int n) {
  return n * n;
}
double doubleSquare(double d) {
  return d * d;
}
dynamic dynamicSquare(dynamic val) {
  return val * val;
}

String

การประกาศ และระบุตัวแปรประเภท String ในแบบต่างๆ

void main() {
  var s1 = 'Single quotes work well for string literals.';
  print(s1);

  var s2 = "Double quotes work just as well.";
  print(s2);

  var s3 = 'It\'s easy to escape the string delimiter.';
  print(s3);

  var s4 = "It's even easier to use the other delimiter.";
  print(s4);

  var s = r'In a raw string, not even \n gets special treatment.';
  print(s);

  /*
  Output:

  Single quotes work well for string literals.
  Double quotes work just as well.
  It's easy to escape the string delimiter.
  It's even easier to use the other delimiter.
  In a raw string, not even \n gets special treatment.
  */
}

String interpolation

void main() {
  var age = 30;
  var str = 'My age is: $age';
  print(str);
}

Multiline String

void main() {
  var s1 = '''
  You can create
  multi-line strings like this one.
  ''';

  var s2 = """This is also a
  multi-line string.""";

  print(s1);
  print(s2);
}

Types Conversion

สามาร Convert type ของตัวแปร ได้ตามตัวอย่างครับ

void main() {
  // String -> int
  var one = int.parse('1');
  assert(one == 1);

  // String -> double
  var onePointOne = double.parse('1.1');
  assert(onePointOne == 1.1);

  // int -> String
  String oneAsString = 1.toString();
  assert(oneAsString == '1');

  // double -> String
  String piAsString = 3.14159.toStringAsFixed(2);
  assert(piAsString == '3.14');
}

Constant and Final

ในขณะ Compile โปรแกรม constant value and final variable จะถูก Set เพียงครั้งเดียว และจะไม่สามารถเปลี่ยนแปลงค่าได้

ตัวอย่าง Constant

void main() {
  const aConstNum = 0; // int constant
  const aConstBool = true; // bool constant
  const aConstString = 'a constant string'; // string constant

  print(aConstNum);
  print(aConstBool);
  print(aConstString);

  print(aConstNum.runtimeType);
  print(aConstBool.runtimeType);
  print(aConstString.runtimeType);
}

ตัวอย่าง Final

void main() {
  final amount = 5;
  print(amount);
}

Null object

กรณีที่ประกาศตัวแปรแต่ไม่ได้ assign ค่า ตัวแปรจะกลายเป็น null object

void main() {
  int num;
  print(num); // output: null
}

Null Aware Operator

Null Aware Operator (?.) ดูตัวอย่างเลยครับ

void main () {
  Num n1;
  Num n2;
  var number1;
  var number2;

  number1 = n1?.num; // value is null
  // error null
  //number2 = n2.num;

  print("number1 is: ${number1}");
  //print("number2 is: ${number2}");
}

class Num {
  int num = 10;
}

Null Aware Operator (??), ถ้า value ในตัวแปรเป็นค่า null จะใช้ค่า Default ที่กําหนด ตัวอย่างเช่น

void main () {
  int n1;
  int number1;

  number1 = n1 ?? 100; // value is 100

  print("number1 is: ${number1}"); // Output: number1 is: 100
}

Null Aware Operator (??=), ถ้า value ในตัวแปรเป็นค่า null จะใช้ค่า Default ที่กําหนด ให้กับตัวแปรนั้นๆ ตัวอย่างเช่น

void main () {
  int number1;

  number1 ??= 200; // value is 200

  print("number1 is: ${number1}"); // Output: number1 is: 200
}

Ternary Operator

Ternary Operator คือ การเขียนตัดสินใจหรือ If…Else… แบบสั้นๆ ลองดูตามตัวอย่างนี้ครับ

void main () {
  int a = 10;

  String text = a == 10 ? "a is 10" : "a is not 10";

  print(text); // Output: a is 10
}

Type Test

is ตรวจสอบ Type ของตัวแปร

ตัวอย่าง

void main () {
  int x = 100;

  if (x is int) {
    print("x is int");
  }else{
    print("x is not int");
  }
}

Cascade notation

(..) Cascades (..) allow you to make a sequence of operations on the same object.

void main () {
  querySelector('#confirm')
  ..text = 'Confirm'
  ..classes.add('important')
  ..onClick.listen((e) => window.alert('Confirmed!'));

  // เท่ากัน

  querySelector('#confirm').text =Confirm’;
  querySelector('#confirm').classes.add('important');
  querySelector('#confirm').onClick .listen((e) => window.alert('Confirmed!'));
}

Collection list

การใช้ Collection list ตามตัวอย่างนี้เลยครับ

void main() {
  List names = ['Thiti', 'Bee'];
  print("Name count is: ${names.length}");
  for (var n in names) {
    print(n);
  }

  print("---------------------------------------");

  List <int> ages = [18, 20, 33];
  for (var a in ages) {
    print(a);
  }
}

Spread Operator

ใช้ (…) เหมือนกับ JavaScript เลยครับ

ตัวอย่าง

void main() {
  var list = [1, 2, 3];
  var list2 = [0, ...list];
  print(list2);
}

Null Aware Spread Operator

ใช้ (…?) เพื่อ Check null ก่อนที่จะ Spread Operator

ตัวอย่าง

void main() {
  var list;
  var list2 = [0, ...?list]; // ถ้าเป็น null จะตัดทิ้ง เหลือแค่ [0]
  print(list2); //Output is [0]
}

Collection if and collection for

การใส่ Condigtion if และ repetition for ใน Array

ตัวอย่าง

void main() {
  var listOfInts = [2,5,7];
  var promoActive = true;

  var nav = [
    'Home',
    'Furniture',
    'Plants',
    for (var i in listOfInts) '#$i',
    if (promoActive) 'Outlet'
  ];

  print(nav);
}

Maps

ประกาศตัวแปรประเภท Map ซึ่งสามารถใช้เก็บข้อมูลในแบบ Key, Value

ตัวอย่าง

void main() {
  var gifts = {
    // Key:    Value
    'first': 'partridge',
    'second': 'turtledoves',
    'fifth': 'golden rings'
  };

  var nobleGases = {
    2: 'helium',
    10: 'neon',
    18: 'argon',
  };

  // You can create the same objects using a Map constructor:

  var gifts = Map();
  gifts['first'] = 'partridge';
  gifts['second'] = 'turtledoves';
  gifts['fifth'] = 'golden rings';

  var nobleGases = Map();
  nobleGases[2] = 'helium';
  nobleGases[10] = 'neon';
  nobleGases[18] = 'argon';
}

Named Parameter

สามารถระบุ name ภายใน parameter ได้

ตัวอย่าง

void main() {
  print(sumName(num1: 2, num2: 2));
}

dynamic sumName({var num1, var num2}) => num1 + num2;

สําหรับ EP นี้เราก็ได้เรียนรู้ Syntax ของภาษา Dart กันไปเรียบร้อยแล้วนะครับ

แล้วพบกัน EP หน้านะครับ ขอบคุณครับ


Copyright © 2019 - 2024 thiti.dev |  v1.19.0 |  Privacy policy |  status | 

            วงแหวนเว็บ