1. 변수 선언
import 'data.dart';
int n1 = 1;
double d1 = 10.1;
bool b1 = true;
String s1 = "홍길동";
void main() {
print(n1.runtimeType); // n1 의 타입 확
print("d1 : " + d1.toString());
print("b1 : ${b1}");
print(s1);
print(secret); // 외부 변수를 출력
}
dart 의 변수는 1급 객체이다. 외부에서 변수만 설정해도 메모리에 변수가 떠 불러올 수 있다.


// 타입 추론 (자바의 오브젝트)
var n1 = 1; // 1이 들어올 때 타입이 결정됨.
dynamic n2 = 2;
void main() {
print(n1.runtimeType);
// int n2 = n1 ;
// n1 = 2.0 ;
// String n2 = n1 ;
//var 은 값이 한 번 정해지면 타입 변경 불가능.
print(n2.runtimeType);
n2 = 2.0;
print(n2.runtimeType);
//dynamic 은 타입 변경이 가능하다.
}
var 타입은 데이터를 받을 때 타입이 결정. 변경 불가능하다.
dynamic 타입은 받을 때 데이터 결정되며, 변경 가능하다.

2. 연산자
void main() {
//산술 연산자
print("3+2=${3 + 2}");
print("3-2=${3 - 2}");
print("3*2=${3 * 2}");
print("3/2=${3 / 2}");
print("3%2=${3 % 2}");
print("3~/2=${3 ~/ 2}");
//비교 연산자
print("2==3 -> ${2 == 3}");
print("2<3 -> ${2 < 3}");
print("2>3 -> ${2 > 3}");
print("2<=3 -> ${2 <= 3}");
//논리 연산자
print("!true -> ${!true}");
print("true&&true -> ${true && false}");
print("true&&true -> ${true && true}");
print("true||false -> ${true || false}");
}

3. 조건문
void main() {
//if문
int point = 70;
if (point >= 90) {
print("A학점");
} else if (point >= 80) {
print("B학점");
} else if (point >= 70) {
print("C학점");
} else {
print("F학점");
}
//삼항 연산자
int point1 = 60;
print(point1 >= 60 ? "합격" : "불합격");
//null 대체 연산자
String? username = null;
print(username);
print(username ?? "홍길동"); // username이 있으면 출력, 없으면 null을 출
}
dart에서는 null 값을 허용하지 않아 String username ; 은 변수로 선언되지 않는다. 이때 ? 를 사용하면 null 값을 허용하게 된다.


4. 함수
함수란 하나의 특별한 목적의 작업을 수행하기 위해 독립적으로 설계된 코드의 집합이다.
함수를 사용하면 반복적인 프로그래밍을 피하고 코드를 재사용할 수 있어, 모듈화가 가능하고 가독성이 좋아진다.
기본 함수
int f(int n){ //int : 리턴 타입, f : 함수명, (int n): 매개변수
return n+1 ; // return n+1 : 반환 값
}
int addOne(int n) {
return n + 1;
}
void main() {
int result = addOne(2);
print("결과 : ${result}");
}

void gugudan(int num) {
print("${num}*1=${num * 1}");
print("${num}*2=${num * 2}");
print("${num}*3=${num * 3}");
print("${num}*4=${num * 4}");
print("${num}*5=${num * 5}");
print("${num}*6=${num * 6}");
print("${num}*7=${num * 7}");
print("${num}*8=${num * 8}");
print("${num}*9=${num * 9}");
}
void main() {
gugudan(4);
}

함수를 만들어놓고 매개변수만 넣으면 원하는 값을 받을 수 있다.
익명 함수
익명 함수는 함수에 이름이 없다. 익명 함수에는 return 키워드를 꼭 적어야 한다.
(매개변수){동작 혹은 반환값}
Function add = (int n1, int n2) {
print(n1 + n2);
};
void main() {
add(1, 3);
}

람다식
함수를 하나의 식으로 표현한다. (매개변수) ⇒ 동작 혹은 반환값
void main() {
//람다식
Function addOne = (n) => n + 1;
print(addOne(2));
Function addTwo = (n) {
return n + 2;
};
print(addTwo(2));
}

5. 클래스
클래스란 현실 세상에 존재하는 대부분의 것들을 클래스로 표현할 수 있다. 프로그래밍 세상에서 객체란 메모리에 로드될 수 있는 것을 말하며, 객체가 될 수 없다는 것은 메모리에 로드할 수 없다는 것을 뜻한다.
class Dog {
String name = "Toto";
int age = 13;
String color = "white";
int thirsty = 100;
}
void main() {
Dog d1 = Dog();
print("이름은 ${d1.name}");
print("나이는 ${d1.age}");
print("색깔은 ${d1.color}");
print("목마름 지수는 ${d1.thirsty}");
Dog d2 = Dog();
d2.thirsty = 50;
print("목마름 지수는 ${d2.thirsty}");
}

Dog 가 목이 말라 thirsty 변수 값을 50으로 변경했다. 이것은 마법이다. 목이 마르면 물을 마시는 행위를 해야 목마름이 해결된다.
class Dog {
String name = "Toto";
int age = 13;
String color = "white";
int thirsty = 100;
void drinkWater(Water w) {
w.drink();
thirsty = thirsty - 50;
}
}
class Water {
double liter = 2.0;
void drink() {
liter = liter - 0.5;
}
}
void main() {
Dog d1 = Dog();
Water w1 = Water();
d1.drinkWater(w1);
print("남은 물의 양 ${w1.liter}");
print("갈증 지수는 ${d1.thirsty}");
d1.drinkWater(w1);
print("남은 물의 양 ${w1.liter}");
print("갈증 지수는 ${d1.thirsty}");
}

물을 마시는 행위를 통해 목마름을 해결한다. 객체란 상태와 행위를 가지며, 행위를 통해 상태를 변경한다.
생성자
생성자는 클래스를 객체로 만들 때 초기화를 위한 함수이다.
class Dog {
String name;
int age;
String color;
int thirsty;
Dog(this.name, this.age, this.color, this.thirsty);
}
void main() {
Dog d1 = Dog("toto", 13, "white", 100);
Dog d2 = Dog("mango", 2, "white", 50);
print("d1의 이름은 ${d1.name}");
print("d2의 이름은 ${d2.name}");
}

선택적 생성자
선택적 생성자는 dart에서 오버로딩 대신 사용하며, 선택적으로 매개변수를 받을 수 있다.
함수({매개변수,매개변수})
선택적 매개변수를 쓰고, 꼭 필요한 데이터는 required 를 사용, null 이 가능하면 ? 를 사용해야 한다.
class Dog {
String name; // new 될때 받기
int age; // 기본값 0
String color; // new 될 때 받기
int thirsty; // 기본값 0
Dog(this.name, this.age, this.color, this.thirsty); // 기본 생성자
Dog.select(
{required this.name,
this.age = 0,
required this.color,
this.thirsty = 0}); // 선택적 매개변수를 쓰는게 좋음
void main() {
Dog d1 = Dog("토토", 0, "흰색", 0);
Dog d2 = Dog.select(
color: "흰색", name: "토토"); // 생성자의 순서대로 값을 넣지 않아도 됨. 키 :값 형식으로 되서 가독성도 좋음
print(d1.age);
print(d1.name);
print(d2.age);
print(d2.name);
}

Share article