Future는:
"나중에 받을 값"
입니다.
즉:
아직 결과는 없지만
미래에 결과가 도착할 예정
이라는 의미입니다.
피자를 주문하면:
바로 안 오고
조금 뒤에 도착
합니다.
이 상태가:
Future
입니다.
import 'dart:async';
void main() {
print("시작");
Future.delayed(
Duration(seconds: 2),
() {
print("2초 뒤 실행");
},
);
print("끝");
}
시작
끝
(2초 뒤)
2초 뒤 실행
Future는
"지금 안 하고 나중에 실행 예약"
입니다.
then()은:
"Future 끝나면 실행해줘"
입니다.
import 'dart:async';
void main() {
print("다운로드 시작");
downloadImage().then((value) {
print(value);
});
print("다른 작업 중...");
}
Future<String> downloadImage() {
return Future.delayed(
const Duration(seconds: 2),
() {
return "이미지 다운로드 완료!";
},
);
}
다운로드 시작
다른 작업 중...
(2초 뒤)
이미지 다운로드 완료!
then()은
Future 완료 후 실행할 코드를 등록
합니다.
옛날에는:
a().then((v1) {
b().then((v2) {
c().then((v3) {
});
});
});
처럼 작성.
들여쓰기 지옥
(callback hell)
발생.
async
await
입니다.
비동기 코드를
동기 코드처럼 읽기 쉽게 만든 문법
입니다.
import 'dart:async';
void main() async {
print("앱 시작");
await loadImage();
print("다음 작업 실행");
}
Future<void> loadImage() async {
print("이미지 다운로드 시작");
await Future.delayed(
const Duration(seconds: 2),
);
print("이미지 다운로드 완료");
}
앱 시작
이미지 다운로드 시작
(2초 뒤)
이미지 다운로드 완료
다음 작업 실행
async
↓
"이 함수는 비동기 함수"
라는 의미.
await
↓
"Future 끝날 때까지 기다려!"
라는 의미.
await는 반드시 async 함수 안에서만 사용 가능
Future<String> doSomething() async {
return 'I am done.';
}
Future.value('I am done.')
처럼 동작.
Future<String> doSomething() {
return Future.value('I am done.');
}
| async 있음 | async 없음 |
|---|---|
| await 사용 가능 | await 사용 불가 |
| 자동 Future 변환 | 직접 Future 반환 |
| 비동기 함수 선언 | 일반 함수 |
downloadImage().then((value) {
print(value);
});
String result =
await downloadImage();
print(result);
| then | async/await |
|---|---|
| callback 스타일 | 동기처럼 읽힘 |
| 중첩 가능 | 순서 명확 |
| 옛날 스타일 느낌 | 최신 스타일 |
Flutter 앱은:
등 시간이 걸리는 작업이 많음.
앱 멈춤
UI는 계속 동작
| 키워드 | 의미 |
|---|---|
| Future | 미래 값 |
| then | 완료 후 실행 |
| async | 비동기 함수 |
| await | 결과 기다림 |
Future는 "나중에 받을 값"이고,
async/await는
그 Future를 동기 코드처럼
읽기 쉽게 만든 문법이다.
예제
//동기 비동기의 이해
// void first_work(){
// print("첫번째 작업 중입니다. 예)구구단 작업");
// }
//
// void second_work(){
// // 인터넷
// // DB
// // 파일
// // 다운로드
// // Firebase
// print("시간이 걸리는 작업 예)이미지(게임) 다운로드 중입니다.");
// }
//
// void third_work(){
// print("3번째 작업(음악듣기) 중입니다.");
// }
//
// Future<void> downloadGame() {
//
// return Future.delayed(
// const Duration(seconds: 2),() {
// print(" 2번찌 작업 다운로드 완료");
// },
// );
// }
//
// void main(){
// first_work();
// //second_work();
// //downloadGame();
// third_work();
// }
// Future<String> fetchUserName(int id) {
//
// return Future.delayed(
// Duration(seconds: 1),
// () {
// if (id <= 0) throw ArgumentError('잘못된 ID');
// return '사용자_$id';
// },
// );
// }
//
// void main() {
//
// fetchUserName(-1)
// .then((name) {
// // 성공 시 처리
// print('이름: $name');
// return name.toUpperCase(); // 다음 then으로 변환된 값 전달
// }).then((upperName) {
// print('대문자: $upperName');
// }).catchError((error) {
// // 에러 처리
// print('오류: $error');
// }).whenComplete(() {
// // 성공/실패 관계없이 항상 실행
// print('작업 완료');
// });
// }
//아래의 두개는 같은 거임
//차이점
//async 있음 async 없음
//await 사용 가능 await 사용 불가
//자동 Future 변환 직접 Future 반환
//비동기 함수 선언 일반 함수
Future<String> fetchWeather(String city) {
return Future(() {
// 실제로는 HTTP 요청을 하겠지만
// 여기서는 시뮬레이션
return '$city의 날씨: 맑음, 22°C';
});
}
Future<String> fetchWeather2(String city) async {
return '$city의 날씨: 맑음, 22°C';
}
void main() async {
var weather = await fetchWeather('서울');
print(weather);
weather = await fetchWeather('서울');
print(weather);
}
import 'package:http/http.dart' as http;
// void main() async{
//
// print("네이버 요청 시작");
//
// final response = await http.get(
// Uri.parse('https://www.naver.com'),
// );
//
// print("응답 완료");
//
// // 📌 HTML 내용 출력
// print(response.body);
// }
void main() {
print("네이버 요청 시작");
http.get(
Uri.parse('https://www.naver.com'),
).then((response){
// 📌 HTML 내용 출력
print(response.body);
});
print("응답 완료");
}