[Flutter] 인터넷 데이터 가져오기

CheolHyeon Park·2021년 2월 21일
2

flutter

목록 보기
1/5

1. http 패키지 설치하기

dependencies:
  http: <latest_version>

pubspec.yaml파일에 http 패키지의 의존성 부분을 추가한다.

그리고 http를 사용하기 위해

import 'package:http/http.dart' as http;

로 패키지를 import 한다.

2. 네트워크 요청하기

import 'package:http/http.dart' as http;

Future<httpp.Response> fetchPost() {
	return http.get("Url");
}

http.get()을 이용하여 해당 URL로 요청을 보낸다.

  • 여기서 Future의 경우 Dart에서 사용하는 비동기 자료형에 해당한다. 미래에 어떤 데이터가 들어올 값이나 에러를 핸들링한다.
  • http.Response클래스는 http 요청이 성공했을 때, 응답으로 받는 데이터를 갖고 있다.

3. 응답 정보를 커스텀 Dart 객체로 변환하기

네트워크 요청 생성은 쉽지만, 그 응답을 상용하는것은 편하지 않다.

우선, 응답을 받을 수 있는 클래스를 생성한다.

class post {
	final int userId;
	final int id;
	final String title;
	final String body;

	Post({this.userId, this.id, this.title, this.body});

	factory Post.fromJson(Map<String, dynamic> json) {
		return Post(
			userId: json['userId'],
			id: json['id'],
			title: json['title'],
			body: json['body'],
		);
	}

}

위와 같이 Post 클래스에 factory함수를 만들어 응답을 처리한다.

그리고 fetchPost()의 응답을 처리한다.

Future<Post> fetchPost() async {
	final response = await http.get('URL');
	if ( response.statusCode == 200) {
		return Post.fromJson(json.decode(response.body));
	} else {
		throw Exception('Failed to load post');
	}
}

4. 데이터 가져오기

위의 fetch 메소드는 다음과 같이 사용한다.

class _MyAppState extends State<MyApp> {
	Future<Post> post;

	
	void initstate() {
		super.initState();
		post = fetchPost();
	}
}

5. 데이터 보여주기

Future데이터를 보여주기 위해서는 FutureBuilder 위젯을 사용하면 된다.

FutureBuilder는 데이터를 가져오기 전, 로딩이나 가져온 후, Connection 상태에 따라 핸들링 할 수 있게 해준다.

FutureBuilder<Post>(
	future: post,
	builder: (context, snapshot) {
		if (snapshot.hasData) {
			return Text(snapshot.data.title);
		} else if (snapshot.hasError) {
			return Text("${snapshot.error}");
		}

		return CircularProgreeIndicator();
	}
)

출처: flutter 공식 홈페이지

profile
나무아래에 앉아, 코딩하는 개발자가 되고 싶은 박철현 블로그입니다.

0개의 댓글