0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Flutter入門】fixerAPIを用いた為替レート変換アプリ作成

Last updated at Posted at 2025-01-19

はじめに

Flutterを始めるにあたって、簡単なアプリを作成してみたいと思います。

fixerのAPIを用いて、為替レート変換を行うアプリです。

事前準備

事前にfixerのAPIキーを取得して控えておきます。

以下のURLからfixerの無料アカウントを作成します。

以下のplanページから$0プランのサブスクライブに進みます。

諸々の情報を入力することでアカウント作成が完了しAPIキーが発行されます。

以下のダッシュボードからAPIキーを確認できます。

無料プランでは1ヶ月あたり100リクエストまでなので、個人の検証用途になるかと思います。

手順

  1. Flutterのインストール
  2. Flutterプロジェクトの作成
  3. コードの記述
  4. 動作確認

1.Flutterのインストール

以下のコマンドを実行します。

mac

brew install --cask flutter

windows

choco install flutter

必要に応じてPATHの設定をしておきます。

Flutterのセットアップ

以下のコマンドを実行して、セットアップを完了させます。

flutter doctor

[✗] と表示されている項目はセットアップ未完了ですので、掲示されるコマンドの実行や必要なソフトのインストールを行います。

2.Flutterプロジェクトの作成

任意の作業ディレクトリを作成してcdしておきます。

該当のディレクトリにて以下のコマンドを実行します。

作業ディレクトリ配下にflutterプロジェクトの雛形がダウンロードされます。

user/work > flutter create exchange-rate

3.コードの記述

以下のファイルを作成してコードを記述します。

exchange-rate/lib/screens/exchange_rate_screen.dart

import 'package:flutter/material.dart';
import '../services/exchange_rate_service.dart';

class ExchangeRateScreen extends StatefulWidget {
  @override
  _ExchangeRateScreenState createState() => _ExchangeRateScreenState();
}

class _ExchangeRateScreenState extends State<ExchangeRateScreen> {
  String? _fromCurrency = 'USD';
  String? _toCurrency = 'JPY';
  double? _exchangeRate;
  final TextEditingController _amountController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('為替レート変換アプリ')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(
              controller: _amountController,
              decoration: const InputDecoration(labelText: '金額を入力'),
              keyboardType: TextInputType.number,
            ),
            const SizedBox(height: 16),
            DropdownButton<String>(
              value: _fromCurrency,
              items: ['USD', 'EUR', 'JPY']
                  .map((currency) =>
                      DropdownMenuItem(value: currency, child: Text(currency)))
                  .toList(),
              onChanged: (value) {
                setState(() {
                  _fromCurrency = value;
                });
              },
              hint: const Text('送金元通貨を選択'),
            ),
            DropdownButton<String>(
              value: _toCurrency,
              items: ['USD', 'EUR', 'JPY']
                  .map((currency) =>
                      DropdownMenuItem(value: currency, child: Text(currency)))
                  .toList(),
              onChanged: (value) {
                setState(() {
                  _toCurrency = value;
                });
              },
              hint: const Text('送金先通貨を選択'),
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: () async {
                if (_fromCurrency != null &&
                    _toCurrency != null &&
                    _amountController.text.isNotEmpty) {
                  try {
                    final rate = await ExchangeRateService.fetchExchangeRate(
                        _fromCurrency!, _toCurrency!);
                    setState(() {
                      _exchangeRate = rate;
                    });
                  } catch (e) {
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(content: Text('エラーが発生しました: $e')),
                    );
                  }
                } else {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('すべての項目を入力してください')),
                  );
                }
              },
              child: const Text('変換'),
            ),
            const SizedBox(height: 16),
            if (_exchangeRate != null)
              Text(
                '変換レート: $_exchangeRate',
                style: const TextStyle(fontSize: 18),
              ),
          ],
        ),
      ),
    );
  }
}

exchange-rate/lib/services/exchange_rate_service.dart

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

class ExchangeRateService {
  static const String _baseUrl = 'https://data.fixer.io/api/latest';
  static const String _apiKey = 'your-api-key'; // FixerのAPIキーを設定してください

  // 為替レートを取得する関数
  static Future<double?> fetchExchangeRate(String from, String to) async {
    final url = Uri.parse(
      '$_baseUrl?access_key=$_apiKey&base=$from&symbols=$to',
    );

    final response = await http.get(url);

    if (response.statusCode == 200) {
      final data = json.decode(response.body);
      if (data['success'] == true) {
        return data['rates'][to];
      } else {
        throw Exception('API Error: ${data['error']['info']}');
      }
    } else {
      throw Exception('Failed to fetch exchange rate: ${response.statusCode}');
    }
  }
}

exchange-rate/lib/main.dart

import 'package:flutter/material.dart';
import 'screens/exchange_rate_screen.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '為替レート変換アプリ',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: ExchangeRateScreen(),
    );
  }
}

4.動作確認

以下のコマンドを実行します。

$ flutter run
Checking for wireless devices...

[1]: macOS (macos)
[2]: Mac Designed for iPad (mac-designed-for-ipad)
[3]: Chrome (chrome)
Please choose one (or "q" to quit): 3

devices(エミュレーター)を選択するために任意の数字(1~3)を入力します。

3(chrome)を選択したので、以下のような画面が開きます。

(開発者ツールの設定を変更することでiosの画面サイズで確認できます)

image.png

金額を入力して変換元をEUR,変換先をUSDにして変換を選択すると結果が表示されました。

image.png

まとめ

今回は、Flutterで簡単なアプリを作成してみました。サーバーが必要なアプリの作成も試していきたいと思います〜

無料プランだと変換元にEURしか使えないようでした。。orz

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?