프로그래밍/flutter

[flutter] 인터넷에서 데이터 가져오기 GET/POST (fetch)

소행성왕자 2023. 10. 25. 09:43

목적 : flutter 를 이용하여 인터넷에서 웹페이지 가져오는 방법 

1. pubspec.yaml  http 모듈 추가

dependencies:
  http: ^0.13.6

http 패키지를 가져옵니다.

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

또한 AndroidManifest.xml 파일에 인터넷 권한을 추가하세요.

<!-- Required to fetch data from the internet. -->
<uses-permission android:name="android.permission.INTERNET" />

2. 네트워크 요청하기

Future<void> fetchPrdCd() async {
  final response = await http.get(Uri.parse('http://abcd.com/quics'));
  if(response.statusCode == 200) {

    print('>>>환율위젯받아옴'+response.body);

  } else {
    throw Exception("Failed to fetchPrdCd");
  }
}

 http.get()메서드는 가 Future 포함된 을(를) 반환합니다 Response.

  • Future 비동기 작업을 위한 핵심 Dart 클래스입니다. Future 객체는 미래의 특정 시점에 사용할 수 있는 잠재적인 값이나 오류를 나타냅니다.
  • 클래스 http.Response에는 성공적인 http 호출에서 수신된 데이터가 포함되어 있습니다.

3. 데이터 가져오기

class _WebViewAppState extends State<WebViewApp> {
  late final WebViewController controller;

  @override
  void initState() {
    super.initState();

    fetchPrdCd();

 

참고

https://docs.flutter.dev/cookbook/networking/fetch-data

 

Fetch data from the internet

How to fetch data over the internet using the http package.

docs.flutter.dev