Flutter 로컬API 호출

개발자, Bono·2024년 10월 23일

Flutter

목록 보기
1/1
post-thumbnail

API 호출 예시

# pubspec.yaml
dependencies:
	http: ^1.2.2
  • 실제 코드 반영
import 'package:http/http.dart' as http;

Future<void> fetchData() async {
    // localhost 대신 10.0.2.2로 해야 로컬 API를 가져올 수 있다. 
    final url = Uri.http('10.0.2.2', '/products/');
    // final url = Uri.https('test.com', '/products/');
    final response = await http.get(url);
    if (response.statusCode == 200) {
      setState(() {
        _data = json.decode(convert.utf8.decode(response.bodyBytes));
      });
    } else {
      print('Failed to load data: ${response.statusCode}');
    }
  }

0개의 댓글