상세 컨텐츠

본문 제목

[Flutter] 외부 API에서 데이터 가져오기

프로그래밍/Flutter

by 웰치스짱 2023. 2. 18. 20:31

본문

반응형

플러터 앱에서 외부 API를 통해 데이터를 가지고 오려면 http 패키지를 사용해야 합니다.

 

1.  pubspec.yaml 파일에 http패키지를 선언하세요.:

dependencies:
http: ^0.13.4

 

2. 먼저 상단에 해당 패키지를 Import 합니다.:

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

 

 

3. http.get() 매서드를 통해서 아래와 같이 호출합니다. 그 메서드는 Future<http.Response> 형태로 반환합니다.

Future<void> getData() async {
    final url = Uri.parse('https://api.example.com/data');
    final response = await http.get(url);

    if (response.statusCode == 200) {
        // Handle the successful response
        final data = response.body;
        // Do something with the data
    } else {
        // Handle the error
        print('Error: ${response.statusCode}');
    }
}
 

In this example, we make a GET request to https://api.example.com/data and check the response status code. If it's 200 (OK), we handle the successful response by getting the response body and doing something with the data. If it's an error, we print the status code.

 

Note that you'll need to replace https://api.example.com/data with the actual URL of the API endpoint you want to call. Additionally, you may need to pass headers or query parameters to the API, depending on its requirements. You can do this by adding them to the http.get() method call.

반응형

관련글 더보기

댓글 영역