레이블이 개발인 게시물을 표시합니다. 모든 게시물 표시
레이블이 개발인 게시물을 표시합니다. 모든 게시물 표시

2022년 10월 27일 목요일

[Flutter] Dart 문법설명 (try catch, rethrow, finally, assert, forEach, for in, continue, break)

Dart 문법설명을 해보자

중요해보이는 문법 위주로 정리한다.


try catch

//try catch
try {
var num = null;
num ++;
} catch (e) {
print('e : ${e.toString()}');
}
print('finish!');
=>
e : NoSuchMethodError: method not found: '$add' on null
finish!

catch 에 잡힌후, 다음 구문 실행 됨.


try catch rethrow

//try catch rethrow
try {
var num = null;
num ++;
} catch (e) {
print('e : ${e.toString()}');
rethrow;
}
print('finish!');
=>
e : NoSuchMethodError: method not found: '$add' on null
Uncaught TypeError: Cannot read properties of null (reading '$add')Error: TypeError: Cannot read properties of null (reading '$add')

rethrow를 만나고 프로그램 정지됨.


try catch finally

//try catch finally
try {
var num = null;
num ++;
} catch (e) {
print('e : ${e.toString()}');
rethrow;
} finally {
print('print finally!');
}
print('finish!');
=>
e : NoSuchMethodError: method not found: '$add' on null
print finally!
Uncaught TypeError: Cannot read properties of null (reading '$add')Error: TypeError: Cannot read properties of null (reading '$add')

rethrow를 만나도, finally 는 무조건 실행됨.


assert

//assert
var count1 = 10;
assert(count1 == 1); // => Exception has occurred

=>

Uncaught Error: Assertion failed

코드실행 하다 assert 문구 false 면 정지.


var count2 = 10;
assert(count2 == 10); // => pass
print('finish');
=>
finish

assert 문구  true이면 코드 통과


forEach

//forEach()
var collection1 = ['bmw', 'hyundai', 'kia', 'honda'];
collection1.forEach((element) {print('collection1 : ${element}');});
=>
collection1 : bmw
collection1 : hyundai
collection1 : kia
collection1 : honda


for in

//for in
var collection2 = ['bmw', 'hyundai', 'kia', 'honda'];
for(var element in collection2) {
print('collection2 : ${element}');
}


=>
collection2 : bmw
collection2 : hyundai
collection2 : kia
collection2 : honda


continue

//continue
var collection3 = ['bmw', 'hyundai', 'kia', 'honda'];
for(var i=0; i<collection3.length; i++) {
if(i>=2) continue; // => exit to for
print('i=${i}');
}
=>
i=0
i=1

for문에서 continue 를 만나면 for문을 빠져나감.


break

//break
var i = 0;
while(true) {
i++;
print('i=$i');
if(i>=2) break; // => exit to while
}
=>
i=1
i=2

while문에서 break를 만나면 while문을 빠져나감.



---- English ----



Let's explain Dart grammar

Focus on the most important grammar.


try catch

//try catch
try {
var num = null;
num ++;
} catch (e) {
print('e : ${e.toString()}');
}
print('finish!');
=>
e : NoSuchMethodError: method not found: '$add' on null
finish!

After being caught by catch , the next statement is executed.


try catch rethrow

//try catch rethrow
try {
var num = null;
num ++;
} catch (e) {
print('e : ${e.toString()}');
rethrow;
}
print('finish!');
=>
e : NoSuchMethodError: method not found: '$add' on null
Uncaught TypeError: Cannot read properties of null (reading '$add')Error: TypeError: Cannot read properties of null (reading '$add')

Meets rethrow and program halts.

try catch finally

//try catch finally
try {
var num = null;
num ++;
} catch (e) {
print('e : ${e.toString()}');
rethrow;
} finally {
print('print finally!');
}
print('finish!');
=>
e : NoSuchMethodError: method not found: '$add' on null
print finally!
Uncaught TypeError: Cannot read properties of null (reading '$add')Error: TypeError: Cannot read properties of null (reading '$add')

Even if rethrow is encountered, finally is executed unconditionally.


assert

//assert
var count1 = 10;
assert(count1 == 1); // => Exception has occurred

=>

Uncaught Error: Assertion failed

Execute the code and stop if the assert statement is false.


var count2 = 10;
assert(count2 == 10); // => pass
print('finish');
=>
finish

If the assert statement is true, the code will pass.


forEach

//forEach()
var collection1 = ['bmw', 'hyundai', 'kia', 'honda'];
collection1.forEach((element) {print('collection1 : ${element}');});
=>
collection1 : bmw
collection1 : hyundai
collection1 : kia
collection1 : honda


for in

//for in
var collection2 = ['bmw', 'hyundai', 'kia', 'honda'];
for(var element in collection2) {
print('collection2 : ${element}');
}


=>
collection2 : bmw
collection2 : hyundai
collection2 : kia
collection2 : honda


continue

//continue
var collection3 = ['bmw', 'hyundai', 'kia', 'honda'];
for(var i=0; i<collection3.length; i++) {
if(i>=2) continue; // => exit to for
print('i=${i}');
}
=>
i=0
i=1

If continue is encountered in the for statement, the for statement is exited.


break

//break
var i = 0;
while(true) {
i++;
print('i=$i');
if(i>=2) break; // => exit to while
}
=>
i=1
i=2

When a break is encountered in a while statement, the while statement is exited.




2022년 10월 23일 일요일

[Flutter] Future, async, await 사용방법

 async 는 비동기 명령사용시 함수에 사용합니다.

비동기 명령은 네트워크통신으로 서버에서 데이터를 요청할 때 또는 delay time이 필요한 명령을 사용할때 사용합니다.

비동기 명령을 사용하는 이유는, 처리시간이 걸리는 명령(코드)에서 메인쓰레드를 잡아 기다리게하지 않고, 별도 쓰레드에서 처리하기 위해서 입니다. 비동기 명령을 통해, 메인쓰레드에서 하는 터치또는 화면표시 렌더링은 비동기명령 처리 시 기다리지 않고 처리됩니다.

await을 설명하겠습니다. 비동기 명령을 사용하는 함수에서 async를 붙여 사용하는데, 비동기명령을 실행 할 때 await를 명령 또는 함수 앞에 붙여주면, 해당 async 붙인 함수 내에서는 await 를 붙인 함수가 실행될때 까지 기다린 후, 다음 명령을 실행합니다.

Future 는 async 를 붙인 함수의 return값을 반환할때 반환형에 함께 붙여 사용합니다.


---- test code ----

void main() {

    print('test 1');

    print('name: ${getName()}');

    print('test 2');

}

Future<String> getName() async {

    print('test 3');

    var name = await requestName();

    print('test 4');    

    return name;

}

---- run result ----

test1

test2

test3

test4






---- english ----


async is used for functions when using asynchronous commands.


Asynchronous commands are used when requesting data from the server through network communication or when using commands that require delay time.


The reason for using asynchronous commands is to process them in a separate thread, rather than waiting for the main thread to wait for commands (code) that take time to process. With an asynchronous command, the touch or display rendering done in the main thread is processed without waiting when processing the asynchronous command.


Let me explain await. Async is used in a function that uses an asynchronous command. When executing an asynchronous command, if await is added before a command or function, the async function waits until the awaited function is executed and then executes the next command. .


Future is used together with the return type when returning the return value of a function to which async is attached.





2022년 10월 21일 금요일

[Flutter] 서버에 데이터 보내는 방법과 서버에서 데이터 받는 방법

✌ 안녕하세요.

Flutter는 Http post 방식으로 서버에 API 요청 할 때, 파라미터를 넘기는 방법에 대해 설명 합니다. 

http.post 함수를 사용할 때, body 에, 파라미터를 담아서 보냅니다.

json 형태로 작성하되, jsonEncode() 함수에 담아서 보냅니다.

예시) jsonEncode([{'id':1, 'date':'2022-10-21'}, {'id':1, 'date':'2022-10-21'}])


위 와 같이 Flutter에서 서버에 있는 API를 파라미터를 담아 요청 시, 파라미터가 API에 제대로 전달이 되어야만 합니다.

이때 서버의 API 수신 파라미터 수신객체가 Object 로 받으면, 파라미터의 포맷은 Map 형태가 됩니다.

서버의 언어가 JAVA인 경우, 그리고 Spring boot 에서 API를 만들고, 파라미터를 Object로 받으면, LinkedHashMap 형태로 들어옵니다. 

그러면 Map에서 각 항목을 key값으로 꺼내서, 사용해야합니다.

매번 Map에서  각 항목을 key값으로 꺼내와야 하는 번거로움이 생깁니다.

불편하다면, 다른 방법으로, 수신파라미터 형태를 Object로 받지말고 특정객체로 생성하는 걸로 받으면 됩니다.

예를들어, Searched.java파일을 만들어, 변수로, 수신 받을 key값으로 정의합니다.

그러면, Map 형태 대신, Searched 형태로 받을 수 있습니다.

다른 API함수에 대해서도 같은 Searched.dart 파일을 사용하기 위해, 요청하는 Flutter의 요청 함수에서 사용하는 모든 파라미터 를 Searched.java파일에 넣어놓으면 Searched.java 파일하나로 Flutter의 API 요청을 모두 받아서 처리할 수 있습니다.

😄 감사합니다.