출처
•
DartPad로 실습할 수 있다.
•
맨 처음 들어가면 이렇게 적혀있는 코드가 있을것이다.
void main() {
for (int i = 0; i < 5; i++) {
print('hello ${i + 1}');
}
}
Dart
복사
•
출력하면 다음과 같이 나온다.
hello 1
hello 2
hello 3
hello 4
hello 5
Dart
복사
•
생각보다 간단한 문법으로 쉽게 결과가 나오는 것을 알 수 있다.
•
아래에서 부터는 아래의 깃 허브 주소에 있는 소스코드를 한페이지에 정리하였다.
02.print hello glroy.dart
void main() {
print('hello glory');
}
/*
hello glory
*/
Dart
복사
03.valiable.dart
void main() {
var name = '김영광';
print (name);
name = '김광영';
print (name);
}
/*
김영광
김광영
*/
Dart
복사
04.number.dart
void main() {
int number1 = 1;
int number2 = -10;
int number3 = number1-number2;
print(number3);
print(number1+number2);
print(number1/number2);
print(number3*number2);
/*
11
-9
-0.1
-110
*/
double number4 = 0.3;
double number5 = -0.7;
double number6 = (number4 * number5);
print (number6);
/*
-0.21
*/
//그 외적으로 %, ++, --, += 전부 가능
double? number7 =4.0;
print(number7); //4
number7 = 2.0;
print(number7); //2
number7 ??=3.0;
print(number7); //2
number7 = null;
print(number7); //null
number7 ??=3.0; //null일떄만 3.0
print(number7); //3
//그외로 >, <, >=, <=, ==, !=, is int, is String, ||, && 전부가능
}
Dart
복사
05.bool&String.dart
void main() {
bool isTrue = true;
bool isFalse = false;
bool glorybool = (isTrue);
print (glorybool);
/*
* true
*/
String name = '김영광';
String name2 = '2345';
print (name);
print (name + name2);
print (name + ' ' + name2);
print ('${name.runtimeType}, isTure2 $name2');
/*
* 김영광
* 김영광2345
* 김영광 2345
* String, isTure2 2345
* */
var name3 = '김광영';
var number = 20;
print(name3.runtimeType);
/*
* String
* */
//var로 하면 다 알아서 되지만 그래도 가독성있게 선언해주자, 만약에 복잡한 타입의 변수일 경우에는 var를 써줘도 좋다.
}
Dart
복사
06_dynamic.dart
void main() {
dynamic name = '김영광';
print (name);
dynamic number = 1;
print(number);
var name2 = '김광영';
print (name2);
print(name.runtimeType);
print(name2.runtimeType);
name = true;
//name2 = 5; //작동안되는 코드입니다.
//즉 변수를 다시 마음대로 선언할 수 있다.
/*
김영광
1
김광영
String
String
*/
}
Dart
복사
07_null.dart
void main() {
String name = '김영광';
print(name);
//name = null //작동 안되는 코드
String? name2 = '김광영';
name2 = null;
print(name2);
print(name2!);//!를 붙이면 이건 절대로 null이 될수 없다.
/*
* 김영광
* null
* Uncaught TypeError: Cannot read properties of null (reading 'toString')Error: TypeError: Cannot read properties of null (reading 'toString')
* */
}
Dart
복사
08_final&const.dart
void main() {
final String name = '김영광';
print(name);
//name = '김광영'//실행안되는 코드 즉 final은 한번 선언하면 끝
const String name2 = '김광영';
print (name2);
//name2 = '김영'//실행안되는 코드 즉 const은 한번 선언하면 끝
final name3 = '김영광1';
const name4 = '김영광2';
// var가 생략된 형태로 작성 가능
print (name3 + name4);
}
Dart
복사
09_datetime.dart
void main() {
DateTime now = DateTime.now(); //이코드를 실행하는 시간
print(now);
final DateTime now2 = DateTime.now(); //final은 DateTime의 빌드 타입의 시간을 몰라도 실행이 가능함
print(now2); //실행가능
//const DateTime now2 = DateTime.now(); //consts는 DateTime의 빌드 타입의 시간을 알아야 실행이 가능함. 그래서 이건 작동 안됨
}
Dart
복사
10_list.dart
void main() {
List<String> blackpink = ['제니', '지수', '로제', '리사'];
List<int> primenumber = [2, 3, 5, 7, 11];
print (blackpink);
print (primenumber);
print (blackpink[0]);
/*
* [제니, 지수, 로제, 리사]
* [2, 3, 5, 7, 11]
* 제니
* */
print(blackpink.length); //4
blackpink.add('준영');
print(blackpink); //[제니, 지수, 로제, 리사, 준영]
blackpink.remove('로제');
print(blackpink); //[제니, 지수, 리사, 준영]
print(blackpink.indexOf('준영')); //3
}
Dart
복사
11_map.dart
void main() {
//Map은 key value pair방식이다. (한쌍,짝)
//Map은 List의 대괄호와는 반대로 중괄호를 사용한다.
//콜론을 기준으로 왼쪽은 키, 오른쪽은 밸류로 인식한다.
//여러값을 넣고 싶으면 콤마를 기준으로 추가한다.
Map dictionary = {
'apple': '사과',
'banana' : '바나나',
'watermelon' : '수박'
};
print(dictionary); // {apple: 사과, banana: 바나나, watermelon: 수박}
//key값을 넣으면 원하는 value값을 추출할수 있다.
print(dictionary['apple']); //사과
Map<String,String> dictionary_2 = {
'apple': '사과',
'banana' : '바나나',
'watermelon' : '수박'
};
print(dictionary_2); //{apple: 사과, banana: 바나나, watermelon: 수박}
//이번에는 선언 후, 값을 추가하는 방법에 대해 알아보자.
Map dictionary2 = {};
print('------------');
print(dictionary2);
dictionary2.addAll({
'apple': '사과',
'banana' : '바나나',
'watermelon' : '수박'
});
//위와같이 선언 후에 값을 일괄로 할당할 수 있다.
print(dictionary2);
//만약 들어있는 값 중 특정값을 삭제하고 싶다면?
//아래와 같이 remove함수를 사용하여 삭제할 수 있다.
dictionary2.remove('apple');
print(dictionary2);
//그렇다면, 변경은 어떻게 할까?
//변경은 List와 같다. List에서 Index를 사용했지만
//Map은 Key값을 사용한다.
dictionary2['banana'] = '버내너';
//할당한 값대로 변경된것을 확인할수 있다.
print(dictionary2);
//List는 Index를 사용하지만, Map는 Key값을 사용한다는 것을 알수있다.
//이번에는 List에서 다뤘던 2가지 선언방법 중 new를 사용한 선언방법처럼
//Map도 new를 사용하여 선언해보자.
Map dictions = {};
Map distions2 = new Map();
Map dictions3 = new Map.from({
'apple' : '사과',
'banana' : '바나나'
});
//List처럼 .from 을 이용하여 할당도 가능하다.
print(dictions3);
//또한 이 Map으로 사용된 것을 List형태로 변경도 가능하다.
//toList앞에 Keys는 Map의 Key값만 List화 하라는 것을 의미한다.
print(dictions3.keys.toList());
//value만 프린트 하고 싶다면 어떻게 할까? Keys와 반대로.
print(dictions3.values.toList());
//위와같이 변경한 뒤부터는 List처럼 사용할수 있는것이다.
//지난 List에서는 안에 들어갈 값의 타입을 설정할수 있었다.
//Map도 가능하다.
Map<String, int> price = {
'apple' : 2000,
'banana' : 4000,
'watermelon' : 6000
};
//위와같이 지정을 할수 있다. 지정을 안해도 무방하지만
//지정을 하는것이 정확한 데이터의 종류와 개발을 위해서라도 타입을 지정하는게 좋다.
//bool도 가능함
//정말 중요한것. Map에서의 Key는 절대적으로 유니크해야한다.
//무슨말이냐면, 이미 key값으로 apple이 들어있는 상태에서 또 apple에 다른값을 넣으면
//List와는 다르게 추가되지 않고, 덮어씌어진다.
//반드시 1개만 존재할수 밖에 없다는것을 명심할것.
price.addAll({
'grape' : 4500,
});
print (price);//{apple: 2000, banana: 4000, watermelon: 6000, grape: 4500}
price.remove('grape'); //삭제가능
print(price.keys); //(apple, banana, watermelon)
}
Dart
복사
12_set.dart
var citySet = {'서울','수원','오산','부산'};
void main(){
citySet.add('안양'); // 추가
citySet.remove('수원'); // 삭제
print(citySet.contains('서울')); // true
print(citySet.contains('도쿄')); // false
final Set<String> names = {
'glory',
'flutter',
'Black Pink',
};
print(names); //{glory, flutter, Black Pink}
names.add('Jenny');
print(names); //{glory, flutter, Black Pink, Jenny}
}
Dart
복사
13_if&switch.dart
void main(){
int age = 15;
if (age < 18) {
print('미성년자에게는 주류를 판매하지 않습니다.');
} else if (age <= 70) {
print('행복한 음주 되세요');
} else {
print('약주는 조금만 하세요');
}
int difficulty = 2;
switch (difficulty) {
case 1:
print('easy');
break;
case 2:
print('normal');
break;
case 3:
print('hard');
break;
default:
print('please, re-select difficulty.');
}
}
Dart
복사
14_for&while.dart
void main(){
int i = 0;
while (i < 10) {
print(i);
i++;
}
List<String> fruits = ['사과', '배', '포도', '귤', '딸기'];
while(i<fruits.length) {
print('나는 ${fruits[i]}를 좋아해');
i++;
}
List<String> fruits2 = ['사과', '배', '포도', '귤', '딸기'];
for (int i = 0; i<fruits2.length; i++) {
print('나는 ${fruits2[i]}를 좋아해');
}
}
Dart
복사
15_fuction.dart
void main() {
addNum(y:20, x:10);
addNum(x:10, y:30, z:40);
int result = addNum2(y:20, x:10);
int result2 = addNum2(x:10, y:30, z:40);
print ('${result+result2}');
}
// 세계의 숫자 (x,y,z)를 더하고 짝수인지 홀수인지 알려주는 함수
// parameter / argment - 매개변수
// postional parameter - 순서가 중요한 파라미터
// optional parameter - 있어도 되고 없어도 되는 파라미터
// named parameter - 이름이 있는 파라미터 (순서가 중요하지 않다.)
addNum({
required int x,
required int y,
int z = 30,
}) {
int sum = x + y + z;
print('x : $x');
if (sum % 2 == 0){
print('짝수입니다.');
}else{
print('홀수입니다.');
}
}
int addNum2({
required int x,
required int y,
int z = 30,
}) {
int sum = x + y + z;
print('x : $x');
if (sum % 2 == 0){
print('짝수입니다.');
}else{
print('홀수입니다.');
}
return sum;
}
Dart
복사
16_arrow&typedef.dart
void main() {
Operation operation = add;
int result = operation(10, 20, 30);
print (result); //60
operation =substract;
int result2 = operation(10,20,30);
print(result2); //-40
int result3 = calculate(30,40,50,add);
print(result3); //120
}
// signature
typedef Operation = int Function(int x, int y, int z);
// 더하기
int add(int x, int y, int z) => x+y+z;
// 빼기
int substract(int x, int y, int z) => x-y-z;
// 계산
int calculate(int x, int y, int z, Operation operation){
return operation(x, y, z);
}
Dart
복사
끝
안녕하세요
•
한국전자기술연구원 김영광입니다.
•
관련 기술 문의와 R&D 공동 연구 사업 관련 문의는 “glory@keti.re.kr”로 연락 부탁드립니다.
Hello 
•
I'm Yeonggwang Kim from the Korea Electronics Research Institute.
•
For technical and business inquiries, please contact me at “glory@keti.re.kr”