본문 바로가기
개발/Flutter

Flutter 플러터 Rest Api 호출 통신 간단 구현

by SPNK 2024. 3. 16.
반응형

코드 작성

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  // API에서 가져온 데이터를 저장할 리스트
  List<dynamic> _data = [];

  // API를 호출하여 데이터를 가져오는 함수
  Future<void> fetchData() async {
    final response = await http.get(Uri.parse('https://api.example.com/data'));
    
    // 만약 요청이 성공했다면
    if (response.statusCode == 200) {
      // JSON 형식의 응답을 Dart 객체로 변환하여 데이터 리스트에 저장
      setState(() {
        _data = json.decode(response.body);
      });
    } else {
      // 요청이 실패한 경우 에러 메시지 출력
      print('Failed to load data: ${response.statusCode}');
    }
  }

  @override
  void initState() {
    super.initState();
    // initState() 메서드에서 데이터 가져오는 함수 호출
    fetchData();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('REST API Communication'),
        ),
        body: _data.isEmpty
            ? Center(child: CircularProgressIndicator())
            : ListView.builder(
                itemCount: _data.length,
                itemBuilder: (BuildContext context, int index) {
                  // 리스트뷰 아이템에 데이터를 출력
                  return ListTile(
                    title: Text(_data[index]['title']),
                    subtitle: Text(_data[index]['description']),
                  );
                },
              ),
      ),
    );
  }
}
반응형

댓글