앱 개발/Dart

Dart Functions(함수) - Defining a Function, Named Parameters

태기 2024. 5. 8. 20:23

1. Defining a Function

String sayHello(String name) {
  return 'Hello ${name} nice to meet you!';
}

void main() {
  print(sayHello('taek'));
}

기본적인 함수 정의는 자바와 비슷하다.

 

한줄짜리 함수는 fat arrow syntax를 적용시킬 수 있다.

fat arrow syntax는 곧바로 return 하는 거랑 같은 의미이다.

String sayHello(String name) =>'Hello ${name} nice to meet you!';
// 더하기 함수
num plus(num a, num b) => a + b;

void main() {
  print(sayHello('taek'));
}

 

 

2. Named Parameters

flutter에서 자주 사용되는 개념이다.

String sayHello(String name, int age, String country) {
  return "Hello $name, you are $age, and you com from $country";
}

void main() {
  print(sayHello('taek', 20, 'Korea'));
}

named parameter 개념을 적용시키기 전이면 이렇게 각각 파라미터로 받아서 호출할 때 순서대로 작성해줘야한다. 그런데 이 방법은 순서도 까먹을 수 있고, 호출할 때 파라미터만 보고 무엇인지 추측하기 어렵다. 따라서 적용하면 다음과 같다. ( Java에서 힘들었던 부분이였음 ㅜ)

String sayHello({String name, int age, String country}) {
  return "Hello $name, you are $age, and you com from $country";
}

void main() {
  print(sayHello(
    age : 20,
    name : 'taek', 
    country : 'Korea'
  ));
}

매개변수에 중괄호{}를 하고 호출할 때 파라미터에 이름을 붙이면 순서 상관없이 가능하다.

 

하지만, Dart는 여기서 null safety 적용 때문에 null 값이 들어오면 어떡하지? 하면서 컴파일 오류를 낸다.

이거를 해결하는 방법은 2가지가 있다.

첫 번째, default value를 정하는 것이다. 

두 번째, required modifier을 이용하는 것이다.

매개변수 앞에 required를 선언해줘서 해당 argument를 적어주지 않는다면 컴파일에서 에러가 난다.