Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- widget
- materialapp
- icon button
- Cow
- algorithm
- BFS
- scaffold
- flutter
- vm
- stack growth
- create
- Flutter
- file
- System call
- Copy-on-write
- pintos
Archives
- Today
- Total
JunHyeok
[Flutter] 3. Future, async 그리고 await -by 코딩셰프 본문
전체 코드
import 'dart:io';
void main() {
showData();
}
void showData() async {
startTask();
String account = await accessData();
fetchData(account);
}
void startTask() {
String info1 = "요청 수행 시작";
print(info1);
}
Future<String> accessData() async {
String account = "3000원";
Duration time = Duration(seconds: 3);
if(time.inSeconds > 2) {
await Future.delayed(time, (){
account = "7000";
print(account);});
}
return account;
}
void fetchData(String account) {
String info3 = "잔액은 ${account}원 ";
print(info3);
}
void showData() async {
startTask();
String account = await accessData();
fetchData(account);
}
여기서, showData() 함수에서 async 선언자를 사용하였다. 이는 비동기적인 흐름을 갖는다는 뜻이다!
이제, 우리는 account라는 변수를 얻어오기 위해서 accessData() 함수 앞에 await 선언자를 붙여놓는다.
Future<string> accessData() async {
Future<String> accessData() async {
String account = "3000원";
Duration time = Duration(seconds: 3);
if(time.inSeconds > 2) {
await Future.delayed(time, (){
account = "7000";
print(account);});
}
return account;
}
- Future<String>은 결과적으로 String을 반환할 것임을 선언하는 것이다.
- Future<String>는 비동기 작업이 완료된 후 String 타입의 결과를 반환할 것을 나타냅니다.
- async는 비동기적 처리를 한다는 것을 의미한다.
- async 키워드는 해당 함수가 비동기적으로 실행될 것임을 나타내며, 함수 내에서 await를 사용할 수 있게 합니다.
- await Future.delayed는 time 시간 동안 대기한 뒤, 해당 콜백 함수를 실행한다.
- await Future.delayed(time, () {...})는 지정된 time 동안 대기한 후, 콜백 함수 내의 코드를 실행합니다. 이 때, await 키워드는 해당 비동기 작업이 완료될 때까지 함수의 실행을 중단시키고, 완료된 후에 이어서 실행합니다.
void fetchData()
void fetchData(String account) {
String info3 = "잔액은 ${account}원 ";
print(info3);
}
'Flutter > 조금매운맛' 카테고리의 다른 글
[Flutter] 5. Null safety in Flutter -by 코딩셰프 (0) | 2024.06.14 |
---|---|
[Flutter] 4. Future - async 심화학습 -by 코딩셰프 (0) | 2024.06.14 |
[Flutter] 2. 간단한 로그인 페이지 만들기 -by 코딩셰프 (0) | 2024.06.13 |
[Flutter] 1. final과 const 변수 이해하기 (0) | 2024.06.13 |