Flutter 학습: 네트워킹 및 데이터 처리
Flutter 애플리케이션을 개발하면서 네트워킹과 데이터 처리는 매우 중요한 부분입니다. 이 글에서는 HTTP 요청 처리, JSON 데이터 처리, 비동기 프로그래밍에 대해 알아보겠습니다.
1. HTTP 요청: http 패키지 사용법, REST API 통신
Flutter에서 HTTP 요청을 처리하기 위해 http 패키지를 사용할 수 있습니다. 이 패키지는 REST API와의 통신을 쉽게 만들어 줍니다.
http 패키지 설치: 먼저, pubspec.yaml 파일에 http 패키지를 추가합니다.
flutter:
sdk: flutter
http: ^0.13.3
그리고 패키지를 설치합니다.
HTTP GET 요청: 간단한 GET 요청을 보내는 예제입니다.
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('HTTP GET Example'),
),
body: Center(
child: FutureBuilder<Post>(
future: fetchPost(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
return Text('Title: ${snapshot.data!.title}');
}
},
),
),
),
);
}
}
Future<Post> fetchPost() async {
final response =
await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));
if (response.statusCode == 200) {
return Post.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to load post');
}
}
class Post {
final int id;
final String title;
final String body;
Post({required this.id, required this.title, required this.body});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
id: json['id'],
title: json['title'],
body: json['body'],
);
}
}
위의 예제에서 http.get 메서드를 사용하여 JSONPlaceholder API에서 데이터를 가져오고, 이를 Post 객체로 변환합니다.
2. JSON 데이터 처리: jsonDecode, jsonEncode
Flutter에서 JSON 데이터를 처리하기 위해 dart:convert 패키지를 사용합니다. jsonDecode와 jsonEncode 함수를 사용하여 JSON 데이터를 변환할 수 있습니다.
JSON 데이터 디코딩: JSON 문자열을 Dart 객체로 변환합니다.
void main() {
String jsonString = '{"id":1,"title":"Hello","body":"World"}';
Map<String, dynamic> userMap = jsonDecode(jsonString);
var post = Post.fromJson(userMap);
print('Title: ${post.title}, Body: ${post.body}');
}
class Post {
final int id;
final String title;
final String body;
Post({required this.id, required this.title, required this.body});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
id: json['id'],
title: json['title'],
body: json['body'],
);
}
}
JSON 데이터 인코딩: Dart 객체를 JSON 문자열로 변환합니다.
void main() {
var post = Post(id: 1, title: 'Hello', body: 'World');
String jsonString = jsonEncode(post);
print(jsonString);
}
class Post {
final int id;
final String title;
final String body;
Post({required this.id, required this.title, required this.body});
Map<String, dynamic> toJson() {
return {
'id': id,
'title': title,
'body': body,
};
}
}
위의 예제에서 Post 객체를 JSON 문자열로 인코딩하여 출력합니다.
3. 비동기 프로그래밍: Future, async, await
Flutter에서 비동기 작업을 처리하기 위해 Future, async, await 키워드를 사용합니다.
Future: Future는 미래에 완료될 작업을 나타냅니다. 비동기 작업의 결과를 처리할 수 있습니다.
async와 await: async 함수는 Future를 반환하며, await 키워드는 비동기 작업이 완료될 때까지 기다립니다.
예제:
void main() async {
print('Fetching data...');
String data = await fetchData();
print('Data: $data');
}
Future<String> fetchData() async {
await Future.delayed(Duration(seconds: 2));
return 'Hello, World!';
}
위의 예제에서 fetchData 함수는 2초 후에 데이터를 반환합니다. await 키워드를 사용하여 fetchData 함수의 결과를 기다린 후, 데이터를 출력합니다.
HTTP 요청과 비동기 프로그래밍: 앞서 작성한 HTTP GET 요청 예제는 비동기 프로그래밍을 활용한 좋은 예입니다. fetchPost 함수는 비동기적으로 데이터를 가져오고, await 키워드를 사용하여 응답을 기다립니다.
final response =
await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));
if (response.statusCode == 200) {
return Post.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to load post');
}
}
이 글에서는 Flutter에서 HTTP 요청 처리, JSON 데이터 처리, 비동기 프로그래밍에 대해 알아보았습니다. http 패키지를 사용하여 REST API와 통신하고, dart:convert 패키지를 사용하여 JSON 데이터를 변환하며, Future, async, await를 사용하여 비동기 작업을 처리할 수 있습니다. 이러한 기술을 활용하여 강력하고 효율적인 Flutter 애플리케이션을 개발해보세요. Happy Coding!
'프로그래밍 > Flutter' 카테고리의 다른 글
[Flutter] 8. Flutter의 -데이터베이스 및 로컬 저장소- (0) | 2024.06.26 |
---|---|
[Flutter] 7. Flutter의 -내비게이션 및 라우팅- (0) | 2024.06.26 |
[Flutter] 5. Flutter의 -상태 관리- (0) | 2024.06.25 |
[Flutter] 4. Flutter의 -기본 위젯 사용- (0) | 2024.06.23 |
[Flutter] 3. Flutter의 -레이아웃 및 UI 구성- (0) | 2024.06.21 |