Function ในภาษา Dart แบบ return ค่า

wave
มานพ กองอุ่น 16 มิ.ย. 2019 21:42:27 9,250

ตัวอย่างนี้มาเขียน function แบบ return ค่า โดยในที่นี้จะให้ return type เป็น String

void main() {
  String name = 'Manop Kongoon';
  int age = 37;
  double height = 1.75;
  
  final person1 = getMe(name, age, height);
  final person2 = getMe('Naphapat', 35, 1.67);
  
  print(person1);
  print(person2);
}

String getMe(String name, int age, double height) {
  return "Hello, I'm $name.I'm $age years old.I'm $height meters tall";
}

ผลลัพทย์จะได้ดังนี้


Hello, I'm Manop Kongoon.I'm 37 years old.I'm 1.75 meters tall
Hello, I'm Naphapat.I'm 35 years old.I'm 1.67 meters tall

Optional Parameter

หากไม่ระบุ parameter ใน function compiler จะกำหนดให้เป็นค่า null อัตโนมัติ เช่น

final person2 = getMe('Naphapat', 35);

โดยปรับการรับ parameter ของ function ดังนี้

String getMe(String name, int age, [double height]) {

ผลลัพท์

Hello, I'm Naphapat.I'm 35 years old.I'm null meters tall

หากต้องการกำหนดค่าเริ่มต้นของ parameter ก็สามารถทำได้เช่นกัน

String getMe(String name, int age, [double height = 0.0]) {

ผลลัพท์

Hello, I'm Naphapat.I'm 35 years old.I'm 0 meters tall

Named Parameter

เราสามารถกำหนด parameter แบบตั้งชื่อได้ คล้ายๆ โครงสร้าง json ลักษณะดังนี้

void main() {
  String name = 'Manop Kongoon';
  int age = 37;
  double height = 1.75;
  
  final person1 = getMe(name: name, age: age, height: height);
  final person2 = getMe(name: 'Naphapat', age: 35, height: 1.67);
  
  print(person1);
  print(person2);
}

String getMe({String name, int age, double height = 0.0}) {
  return "Hello, I'm $name.I'm $age years old.I'm $height meters tall";
}

ผลลัพท์


CONSOLE
Hello, I'm Manop Kongoon.I'm 37 years old.I'm 1.75 meters tall
Hello, I'm Naphapat.I'm 35 years old.I'm 1.67 meters tall

Arrow Operator

เราสามารถใช้ => ในการเขียน function แบบสั้นได้ดังนี้

void getName(String name) => print("Hello, I'm $name");

 


ความคิดเห็น

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

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

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

มานพ กองอุ่น

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