ตัวแปรในภาษา Dart

wave
มานพ กองอุ่น 16 มิ.ย. 2019 15:54:23 7,929

ตัวอย่างตัวแปรในภาษา Dart

void main() {
  var varname = 123; //ประกาศตัวแปร (อัตโนมัติ)
  String name = 'Manop Kongoon'; // ตัวแปรข้อความ
  int age = 37; // ตัวแปรจำนวนเต็ม
  double height = 1.75; // ตัวแปรแบบจุดทศนิยม
  final birthday = '2019-04-10'; // ตัวแปรคงที่
  dynamic mood = 'good'; // ตัวแปรเปลี่ยน type ได้
  
  // varname = 'Test'; // Error
  
  print("Hello, I'm $name");
  print("My name has ${name.length} letters");
  print("I'm $age years old");
  print("I'm $height meters tall");
  print("My birthday is $birthday");
  
  print("Mood before is $mood");
  mood = 123;
  print("Mood after is $mood");
}

ผลลัพท์

Hello, I'm Manop Kongoon
My name has 13 letters
I'm 37 years old
I'm 1.75 meters tall
My birthday is 2019-04-10
Mood before is good
Mood after is 123

var เป็นการประกาศตัวแปร ซึ่งจะถูกกำหนด type ตั้งแต่แรก เช่นถ้าเรากำหนด var varname = 123; แล้ว type จะกลายเป็น int อัตโนมัติ เป็นต้น ถ้าหากมีการเปลี่ยนแปลงค่าไปเป็น type อื่นๆ จะ error เช่น varname = 'Test'; จะ error เป็นต้น

 


ความคิดเห็น

หากบทเรียนรู้มีความผิดพลาดประการใด หรือมีข้อเสนอแนะกรุณาแจ้ง contact@programmerthailand.com

เขียนบทเรียนรู้ของคุณ

รายละเอียด
  • ดู 7,929
  • รักเลย 0
  • หมวดหมู่ Flutter
  • เขียนเมื่อ
  • แก้ไขเมื่อ
  • Tags dart variable flutter
ข้อมูลผู้เขียน
มานพ กองอุ่น

มานพ กองอุ่น

เป็นสมาชิกเมื่อ: 18 ธ.ค. 2009