코드팩토리의 플러터 프로그래밍 2판 책을 참고하여 공부용으로 작성한 게시글입니다.
📌 async, await
await 를 쓴 함수에 async를 쓴다.
await : 비동기 작업이 완료될 때까지 기다린다.
async : await을 사용한 비동기 함수를 정의하는 키워드. 이 함수의 반환타입은 항상 Future이다.
사용방식
Future<반환타입> 함수명() async{
await 비동기작업;
return 반환;
}
* try-catch로 async/await 코드에서 발생한 에러를 처리한다.
사용예
Future<String> fetchData() async {
await Future.delayed(Duration(seconds: 2)); // 2초 대기
return "Hello, async/await!";
}
void main() async {
String data = await fetchData();
print(data); // 2초 후 출력: Hello, async/await!
}
try-catch
Future<String> fetchData() async {
await Future.delayed(Duration(seconds: 2));
throw Exception("Error fetching data");
}
void main() async {
try {
String data = await fetchData();
print(data);
} catch (e) {
print("Caught error: $e"); // Caught error: Exception: Error fetching data
}
}
HTTP 요청 예제
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<void> fetchData() async {
final response = await http.get(Uri.parse("https://jsonplaceholder.typicode.com/posts/1"));
if (response.statusCode == 200) {
print(jsonDecode(response.body)); // JSON 데이터 출력
} else {
print("Failed to load data");
}
}
void main() async {
await fetchData();
}
#코드팩토리의플러터프로그래밍2판 #공부용
'◼️Flutter' 카테고리의 다른 글
[Dart 3.0] 레코드 (0) | 2025.01.25 |
---|---|
[Flutter Dart] Stream (0) | 2025.01.25 |
[Flutter Dart] 비동기 프로그래밍 - Future (0) | 2025.01.25 |
[Flutter Dart] 캐스케이드 연산자 '..' 키워드 (0) | 2025.01.25 |
[Flutter Dart] static (0) | 2025.01.25 |