flutter(플러터) - 15.동기(sync) 비동기(async)의 이해

JungSik Heo·2026년 5월 10일

flutter

목록 보기
20/23

Dart async / await / Future 정리


1️⃣ Future란?

Future는:

"나중에 받을 값"

입니다.

즉:

아직 결과는 없지만
미래에 결과가 도착할 예정

이라는 의미입니다.


🍔 현실 비유

피자를 주문하면:

바로 안 오고
조금 뒤에 도착

합니다.

이 상태가:

Future

입니다.


Future 예제

import 'dart:async';

void main() {

  print("시작");

  Future.delayed(
    Duration(seconds: 2),
    () {
      print("2초 뒤 실행");
    },
  );

  print("끝");
}

실행 결과

시작
끝

(2초 뒤)

2초 뒤 실행

핵심

Future는
"지금 안 하고 나중에 실행 예약"

입니다.


2️⃣ then() 이란?

then()은:

"Future 끝나면 실행해줘"

입니다.


then 예제

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 완료 후 실행할 코드를 등록

합니다.


3️⃣ callback 방식 문제점

옛날에는:

a().then((v1) {

  b().then((v2) {

    c().then((v3) {

    });

  });

});

처럼 작성.


문제점

들여쓰기 지옥
(callback hell)

발생.


그래서 등장한 것

async
await

입니다.


4️⃣ async / await란?

비동기 코드를
동기 코드처럼 읽기 쉽게 만든 문법

입니다.


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초 뒤)

이미지 다운로드 완료
다음 작업 실행

5️⃣ async 의미

async

"이 함수는 비동기 함수"

라는 의미.


6️⃣ await 의미

await

"Future 끝날 때까지 기다려!"

라는 의미.


📌 중요한 규칙

await는 반드시 async 함수 안에서만 사용 가능

7️⃣ async 쓰고 안 쓰고 차이

async 사용

Future<String> doSomething() async {
  return 'I am done.';
}

내부적으로는

Future.value('I am done.')

처럼 동작.


async 없이 작성

Future<String> doSomething() {
  return Future.value('I am done.');
}

차이점

async 있음async 없음
await 사용 가능await 사용 불가
자동 Future 변환직접 Future 반환
비동기 함수 선언일반 함수

8️⃣ async/await vs then

then 방식

downloadImage().then((value) {

  print(value);
});

async/await 방식

String result =
    await downloadImage();

print(result);

차이

thenasync/await
callback 스타일동기처럼 읽힘
중첩 가능순서 명확
옛날 스타일 느낌최신 스타일

9️⃣ Flutter에서 왜 중요할까?

Flutter 앱은:

  • API 요청
  • 로그인
  • 이미지 다운로드
  • Firebase
  • DB 조회

등 시간이 걸리는 작업이 많음.


동기로 처리하면 😢

앱 멈춤

비동기로 처리하면 😀

UI는 계속 동작

1️⃣0️⃣ 핵심 개념 정리

키워드의미
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("응답 완료");

}
profile
쿵스보이(얼짱뮤지션)

0개의 댓글