flutter future
| topics | 500-모바일개발 501 Flutter 503 Dart |
| types | 이론 레퍼런스 |
| tags | #flutter #future #async |
| references | jinhan38.com/151 dart.dev/codelabs/async-await |
Flutter Future
Dart의 비동기 프로그래밍에서 핵심이 되는 Future 클래스에 대한 설명이다.
What is Future
Future는 비동기 작업의 결과를 나타내는 객체다. 작업이 완료되면 결과값을 반환하거나 에러를 발생시킨다.
왜 Future가 필요할까: 네트워크 요청, 파일 I/O, 데이터베이스 작업 등은 시간이 걸린다. 이런 작업을 동기적으로 처리하면 앱이 멈추기 때문에, 비동기로 처리하고 나중에 결과를 받아야 한다.
Future의 상태
Future는 세 가지 상태를 가진다:
- Uncompleted - 아직 작업이 완료되지 않음
- Completed with value - 작업 완료, 결과값 반환
- Completed with error - 작업 실패, 에러 발생
기본 사용법
async/await 방식 (권장)
Future<String> fetchData() async {
// 네트워크 요청 시뮬레이션
await Future.delayed(Duration(seconds: 2));
return 'Data loaded';
}
void main() async {
print('Loading...');
String result = await fetchData();
print(result); // 2초 후 'Data loaded' 출력
}
왜 async/await를 권장하냐면: 코드가 동기 코드처럼 읽히기 때문에 가독성이 좋다. then 체이닝보다 훨씬 직관적이다.
then 방식
fetchData().then((value) {
print(value);
}).catchError((error) {
print('Error: $error');
});
에러 처리
try-catch (async/await와 함께)
Future<void> loadData() async {
try {
final result = await fetchData();
print(result);
} catch (e) {
print('Error: $e');
} finally {
print('Done');
}
}
catchError (then과 함께)
fetchData()
.then((value) => print(value))
.catchError((error) => print('Error: $error'))
.whenComplete(() => print('Done'));
여러 Future 동시 처리
Future.wait - 모두 완료될 때까지 대기
final results = await Future.wait([
fetchData1(),
fetchData2(),
fetchData3(),
]);
// results는 List<T>로 반환
Future.any - 가장 먼저 완료되는 것만
final firstResult = await Future.any([
fetchFromServer1(),
fetchFromServer2(),
]);
FutureBuilder로 UI 연결
Flutter에서 Future 결과를 UI에 반영할 때 사용한다.
FutureBuilder<String>(
future: fetchData(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
}
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
return Text(snapshot.data ?? '');
},
)
주의: FutureBuilder의 future는 build 메소드 밖에서 초기화해야 한다. build 안에서 하면 rebuild마다 새로운 Future가 생성된다.
관련 문서
- AsyncValue vs AsyncData - Riverpod에서의 비동기 상태 처리
- riverpod read listen - Riverpod의 비동기 데이터 구독