Flutter EP.2 ภาษา Dart

28 May 2020,
Share: 
Cover image

สวัสดีครับ หลังจาก 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 หน้านะครับ ขอบคุณครับ

Suggestion blogs

Review ไฟฉาย JetBeam EC-R16

JetBeam EC-R16 เป็นไฟฉายขนาดเล็ก (2.2 ซม. x ยาว 7.1 ซม. x หัว 2.6 ซม.) ใช้แบตเตอรี่ CR123 หรือ 16340 ก็ได้ ความสว่างสูงสุด 750 Lumens รุ่นนี้สามารถเสียบชาร์จด้วย USB ได้ คุณสมบัติแบบละเอียดดังนี้

Goodbye wordpress, Hello Hugo

สวัสดีครับ กลับมาอีกครั้งหลังจากหายไปไม่ได้เขียน Blog นานมากๆ กลับมาครั้งนี้มีการเปลี่ยนแปลงหลายอย่างครับชื่อเว็บเปลี่ยนจากเดิม www.thitiblog.com เป็น thiti.dev แล้วในตอนนี้ และเปลี่ยนจากเดิมที่ใช้ Wordpress มาเป็น Hugo ก็จะมาเล่าให้ฟังว่า Hugo มันคืออะไร ดีอย่างไง ทําไมถึงหันมาใช้ HugoHugo คืออะไรHugo(static site generator) เป็นเครื่องมือสําหรับสร้างเว็บ Page ที่เป็น Static file ล้วนๆ ไม่ต้องมี Database มีเฉพาะไฟล์ html, css, javascript, image ที่จริงก็มีอีกหลายเจ้า แต่ Hugo จะมีจุดเด่นในเรื่องของความเร็ว และความยืดหยุ่นในการใช้งานHugo ดีอย่างไรเมื่อเป็นเว็บแบบ Static file ทำให้สามารถใช้ Static File Hosting ธรรมดาได้เลย ซึ่งจะมีราคาที่ถูก และบางที่ก็ฟรีเนื่องจาก ไม่ต้องใช้ Database และไม่มีการประมวลผลในส่วนของ Backend เพียงแค่โยนไฟล์ออกไปเท่านั้น ทำให้เว็บเร็วมากๆทำ SEO ได้ดียิ่งขึ้น เนื่องจากเป็นเว็บ แบบ Static fileหมดปัญหาเรื่องการโดน Hack เพราะเว็บทั้งเว็บเป็น Static fileข้อจํากัดของ Hugoไม่สามารถทําเว็บที่มีการเก็บข้อมูลได้ เนื่องจากไม่มี Backend และ Databaseจะต้องมี Hugo ในเครื่องที่ต้องการแก้ไขหรือ เพิ่ม Contentเมื่อมีการ Update content จะต้อง Built ก่อนทําให้ Content จะไม่ถูก Update ในทันทีสรุป Hugo เหมาะกับการสร้างเว็บแบบไหนHugo เป็น Tool สําหรับสร้างเว็บที่เป็น Static website ดังนั้นเว็บที่เหมาะจะเป็นเว็บประเภทเน้นให้บริการ Content เป็นหลัก เช่น Web blog, เว็บแนะนําสินค้า, โรงเรียน ส่วนใหญ่เว็บพวกนี้จะแสดงผลเพียงเนื้อหาอย่างเดียว อาจจะมีการ embedded forms ต่างๆ ได้ เช่น Facebook comment, Form ส่งเมล์ติดต่อสอบถาม, google analytic ฯลฯ จะง่ายในการใช้งาน และจัดการเป็นอย่างมากหลังจากที่ได้ลองเล่น ก็พบว่าเหมาะกับ Web blog ของผมเป็นอย่างมาก เพราะง่ายต่อการจัดการ ระบบไม่ซับซ้อนเกินความจําเป็นสําหรับเว็บที่เน้นนําเสนอข้อมูลเพียงอย่างเดียว และที่สําคัญเป็นมิดรกับ SEO ส่วนในเรื่อง Performance ก็ดีมากเพราะเป็น Static website เราสามารถนําเว็บของเราไปวางที่ Host ไหนก็ได้ ราคาถูก หรือไม่ก็ฟรี อย่างเช่น Google firebase hosting, netlify ฯลฯ ตอนนี้ผมจึงย้ายมาใช้งาน Hugo เป็นที่เรียบร้อย :) ถ้าท่านทําลังมองหาหรือ จะทํา Website ประเภทนี้อยู่ ก็เป็นตัวเลือกที่ดีเลยครับ

กฎการตั้งชื่อในภาษาซี

ในภาษาซีจะมีกฎการตั้งชื่อให้กับ ตัวแปร, function และเลเบล ดังนี้


Copyright © 2019 - 2025 thiti.dev |  v1.59.0 |  Privacy policy | 

Build with ❤️ and Astro.

Github profile   Linkedin profile   Instagram   X profile   Nostr   Youtube channel   Telegram   Email contact   วงแหวนเว็บ