ข้ามไปยังเนื้อหาหลัก
ProgrammerThailand

Flutter

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

ตัวอย่างตัวแปรในภาษา 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 เป็นต้น

 

ติดปัญหาตอนทำตาม? ถามในชุมชน

ความคิดเห็น (0)

ยังไม่มีความคิดเห็น — เริ่มคุยเป็นคนแรก ถามสิ่งที่สงสัย หรือแชร์ประสบการณ์ของคุณ