Flutter - Dart 문법(1)

박선규's avatar
Apr 08, 2024
Flutter - Dart 문법(1)

변수

📌
다트에서 변수는 1급 객체이다.
notion image
notion image
 

타입 확인

void main(List<String> args) { int n1 = 1; double d1 =10.1; bool b1 =true; String s1 = "홍길동"; print("정수 : ${n1.runtimeType}"); print("정수 : ${d1.runtimeType}"); print("정수 : ${b1.runtimeType}"); print("정수 : ${s1.runtimeType}"); }
notion image
 

타입 추론

📌
값이 들어올 때 타입을 추론하여 변수를 초기화 한다.
void main(List<String> args) { var n1 = 1; var d1 = 10.1; var b1 = true; var s1 = "홍길동"; print("정수 : ${n1.runtimeType}"); print("실수 : ${d1.runtimeType}"); print("부울 : ${b1.runtimeType}"); print("문자열 : ${s1.runtimeType}"); }
notion image
 
 

var과 dynamic의 차이

📌
var 타입은 값이 한번 정해지면 타입 변경이 불가능 하고
dynamic은 타입 변경이 가능하다.
// 타입 추론 (자바의 오브젝트) 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 은 타입 변경이 가능하다. }
notion image
main하면 클래스 없이 함수가 바로 튀어나온다 이 뜻은 1급 객체로 바로 메모리에 띄울 수 있다는거다.
 
함수랑 메서드의 차이
함수는 클래스 밖에 있는것을 의미하고
메서드는 클래스 안에 있는것을 의미
 
 
notion image
 

자동 import

String secret = "박선규";
import 'data.dart'; //변수를 누구의 도움없이 메모리에 바로 띄울 수 있다. 변수는 dart에서 객체라는 뜻이다. int n1 = 1; double d1 = 10.1; bool b1 = true; String s1 = "홍길동"; void main() { print(n1.runtimeType); print("d1 : " + d1.toString()); // 묵시적 형변환이 안되므로 형변환을 직접 해줘야 된다. print("b1 : ${b1}"); print(s1); print(secret); }
notion image
notion image
notion image
 

연산자

산술 연산자 (Dart 에는 몫을 구하는 문법이 있다)

void main(List<String> args) { //더하기 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}"); }
notion image
 
 

비교연산자

//비교 연산자 void main() { print("2==3 -> ${2 == 3}"); print("2<3 -> ${2 < 3}"); print("2>3 -> ${2 > 3}"); print("2<=3 -> ${2 <= 3}"); }
notion image
 

논리 연산자

//논리 연산자 void main() { print("!true -> ${!true}"); print("true&&true -> ${true && false}"); print("true&&true -> ${true && true}"); print("true||false -> ${true || false}"); }
notion image
 
 

조건문

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 값을 허용하지 않아서 Stirng username은 변수로 취급 안하므로 선언 되지 않는다. 이때 ‘?’ 를 사용하면 null 값을 허용하게 된다.
notion image
 

함수

📌
하나의 특별한 목적의 작업을 수행 하기 위해서 독립적으로 설계된 코드의 집합이다. 함수를 사용시 반복적인 프로그래밍을 피하고 코드 재사용이 가능하여, 모듈화 가능 및 가독성이 좋아진다.
 

기본 함수

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}"); }
 
notion image
 

익명 함수

📌
이름 처럼 함수에 이름이 없다. 익명 함수에는 return 꼭 적어야한다.
Function add = (int n1, int n2) { print(n1 + n2); }; void main() { add(1, 3); }
 
notion image

람다식

📌
함수를 간추려서 표현 할 수 있다.
void main() { //람다식 (매개변수) => 동작 또는 반환 값 Function addOne = (n) => n + 1; print(addOne(2)); Function addTwo = (n) { return n + 2; }; print(addTwo(2)); }
notion image
 

클래스

📌
현실 세상에 존재하는 대부분의 것들을 클래스로 표현 가능
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가 목말라하고 목마름 지수는 50 이 됨 }
notion image
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}"); }
notion image
 

생성자

📌
생성자는 클래스가 객체가 될 때 초기화를 위한 메서드다.
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}"); }
 
notion image
 

선택적 매개변수

📌
선택적 매개변수를 사용하는 생성자는 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); }
notion image
Share article

p4rksk