[flutter] 플러터 앱에서 GET 메소드를 사용하여 사용자의 금융 거래 내역을 가져오는 방법은 무엇인가요?

플러터(Flutter)는 Google이 개발한 모바일 애플리케이션 개발 프레임워크로, 다양한 플랫폼에서 고성능의 앱을 만들 수 있습니다. 이 문서에서는 플러터 앱에서 사용자의 금융 거래 내역을 가져오는 방법에 대해 알아보겠습니다. 이를 위해 GET 메소드를 사용하여 API 요청을 수행할 것입니다.

단계 1: HTTP 패키지 추가

먼저, HTTP 요청을 보내기 위해 http 패키지를 사용해야 합니다. pubspec.yaml 파일에 아래의 의존성을 추가합니다:

dependencies:
  http: ^0.13.3

의존성을 추가한 후에는 터미널에서 flutter packages get 명령어를 실행하여 패키지를 다운로드하고 프로젝트를 업데이트합니다.

단계 2: GET 요청 보내기

HTTP 패키지를 추가한 후에는 GET 요청을 보내기 위한 코드를 작성할 수 있습니다. 다음은 예시입니다:

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

Future<List<Transaction>> fetchTransactions() async {
  final response = await http.get(Uri.parse('https://api.example.com/transactions')); // API 엔드포인트를 입력하세요.

  if (response.statusCode == 200) {
    final List<dynamic> data = jsonDecode(response.body);
    List<Transaction> transactions = [];

    data.forEach((transactionData) {
      transactions.add(Transaction.fromJson(transactionData));
    });

    return transactions;
  } else {
    throw Exception('Failed to fetch transactions');
  }
}

class Transaction {
  final String id;
  final String description;
  final double amount;

  Transaction({required this.id, required this.description, required this.amount});

  factory Transaction.fromJson(Map<String, dynamic> json) {
    return Transaction(
      id: json['id'],
      description: json['description'],
      amount: json['amount'],
    );
  }
}

위의 코드에서 fetchTransactions 함수는 API 엔드포인트에서 사용자의 금융 거래 내역을 가져옵니다. 이 함수는 http.get을 사용하여 GET 요청을 보내고, 응답을 확인한 후에 가져온 데이터를 처리합니다. JSON 응답을 파싱한 후에는 Transaction 객체의 리스트를 반환합니다.

단계 3: 가져온 데이터를 활용하기

금융 거래 내역을 가져온 후에는 해당 데이터를 플러터 앱에서 활용할 수 있습니다. 예를 들어, 다음은 fetchTransactions 함수를 호출하여 가져온 내역을 ListView에 표시하는 예시입니다:

class TransactionListScreen extends StatefulWidget {
  @override
  _TransactionListScreenState createState() => _TransactionListScreenState();
}

class _TransactionListScreenState extends State<TransactionListScreen> {
  late Future<List<Transaction>> _futureTransactions;

  @override
  void initState() {
    super.initState();
    _futureTransactions = fetchTransactions();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('거래 내역'),
      ),
      body: FutureBuilder<List<Transaction>>(
        future: _futureTransactions,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            final transactions = snapshot.data!;
            
            // transactions 리스트를 이용하여 ListView 구성
            return ListView.builder(
              itemCount: transactions.length,
              itemBuilder: (context, index) {
                final transaction = transactions[index];
                return ListTile(
                  title: Text(transaction.description),
                  subtitle: Text(transaction.amount.toString()),
                );
              },
            );
          } else if (snapshot.hasError) {
            return Text('데이터를 가져오는 데 실패했습니다.');
          }

          return CircularProgressIndicator();
        },
      ),
    );
  }
}

위의 코드에서 fetchTransactions 함수를 호출하여 데이터를 비동기적으로 가져오고, FutureBuilder를 사용하여 데이터가 로딩 중인 경우에는 로딩 인디케이터를 표시합니다. 데이터를 성공적으로 가져온 경우에는 ListView를 구성하여 사용자에게 표시합니다.

이제 플러터 앱에서 사용자의 금융 거래 내역을 가져오는 단계를 완료했습니다. 프로젝트에 맞게 API 엔드포인트 및 데이터 구조를 수정하여 적용하세요.

더 자세한 내용은 플러터 공식 문서를 참조하세요.