Flutter货币转换插件geo_currencies的使用

Flutter货币转换插件geo_currencies的使用

GeoCurrencies

geo_currencies 是一个 Flutter 包,提供了获取货币信息的方法。所有货币转换数据每天更新一次。

特性

  • 通过坐标获取货币数据:该库提供了方法以给定地理坐标获取货币数据。
  • 格式化金额与货币符号:该库提供了方便的方法来格式化带有货币符号的金额。
  • 使用货币进行金额转换:该库提供了方便的方法来转换金额,数据源从 EXCHANGE RATE API 文档 获取。
  • 多语言支持:方法接受可选的 Locale 参数,可以用来指定语言,默认语言为英语。

安装

在你的 pubspec.yaml 文件中添加以下依赖:

dependencies:
  geo_currencies: ^0.0.5

使用

在 Dart 代码中导入包:

import 'package:geo_currencies/geo_currencies.dart';

GeoCurrencies 类实现为接口,具有工厂构造函数,根据可选的 GeoCurrenciesType 返回不同的实例,默认情况下 GeoCurrenciesTypelive

示例代码

以下是一个完整的示例代码,展示了如何使用 geo_currencies 插件进行货币转换。

import 'package:flutter/material.dart';
import 'package:geo_currencies/geo_currencies.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Geo Currencies Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Geo Currencies Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    final GeoCurrencies geoCurrencies = GeoCurrencies(
      config: GeoCurrenciesConfig(
          geoCurrenciesType: GeoCurrenciesType.live,
          decimalDigits: 2,
          decimalSeparator: '.',
          includeSymbol: true,
          symbolSeparator: ' ',
          locale: const Locale('En', 'en'),
          thousandSeparator: ','),
    );

    const TextStyle style1 = TextStyle(
        color: Colors.black87, fontSize: 18, fontWeight: FontWeight.bold);

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        centerTitle: true,
        title: Text(
          widget.title,
          style: const TextStyle(color: Colors.black87),
        ),
      ),
      body: SingleChildScrollView(
        child: Center(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Text(
                'Formats amount with currency symbol',
                style: style1,
              ),
              const SizedBox(
                height: 10,
              ),
              Text(
                geoCurrencies.formatAmountWithCurrencySymbol(
                  amount: 10,
                  currencyCodeIso4217: 'XAF',
                ),
              ),
              const SizedBox(
                height: 40,
              ),
              const Text(
                'Formats amount with currency code',
                style: style1,
              ),
              const SizedBox(
                height: 10,
              ),
              Text(
                geoCurrencies.formatAmountWithCurrencyCode(
                  amount: 1000,
                  currencyCodeIso4217: 'XAF',
                ),
              ),
              const SizedBox(
                height: 40,
              ),
              const Text(
                'Converts amount with rate',
                style: style1,
              ),
              const SizedBox(
                height: 10,
              ),
              Column(
                children: [
                  Text(
                    'amountConverted: ${geoCurrencies.convertAmountWithRate(amount: 10, rate: 0.23, toCurrencyCodeIso4217: 'XAF').amountConverted}',
                  ),
                  Text(
                    'baseAmount: ${geoCurrencies.convertAmountWithRate(amount: 10, rate: 0.23, toCurrencyCodeIso4217: 'XAF').baseAmount}',
                  ),
                  Text(
                    'rate: ${geoCurrencies.convertAmountWithRate(amount: 10, rate: 0.23, toCurrencyCodeIso4217: 'XAF').rate}',
                  ),
                  Text(
                    'formattedAmountConvertedWithCurrencyCode: ${geoCurrencies.convertAmountWithRate(amount: 10, rate: 0.23, toCurrencyCodeIso4217: 'XAF').formattedAmountConvertedWithCurrencyCode}',
                  ),
                  Text(
                    'formattedAmountConvertedWithCurrencySymbol: ${geoCurrencies.convertAmountWithRate(amount: 10, rate: 0.23, toCurrencyCodeIso4217: 'XAF').formattedAmountConvertedWithCurrencySymbol}',
                  ),
                  Text(
                    'toCurrencyCodeIso4217: ${geoCurrencies.convertAmountWithRate(amount: 10, rate: 0.23, toCurrencyCodeIso4217: 'XAF').toCurrencyCodeIso4217}',
                  ),
                ],
              ),
              const SizedBox(
                height: 40,
              ),
              const Text(
                'Gets currency data by coordinate.',
                style: style1,
              ),
              const SizedBox(
                height: 10,
              ),
              FutureBuilder<CurrencyData?>(
                  future: geoCurrencies.getCurrencyDataByCoordinate(
                    latitude: 4.052851963460176,
                    longitude: 9.717363661147893,
                  ),
                  builder: (context, snapshot) {
                    return Column(
                      children: [
                        Text(
                          'names: ${snapshot.data?.name}',
                        ),
                        Text(
                          'countryName: ${snapshot.data?.countryName}',
                        ),
                        Text(
                          'symbol: ${snapshot.data?.symbol}',
                        ),
                        Text(
                          'codeIso4217: ${snapshot.data?.codeIso4217}',
                        ),
                      ],
                    );
                  }),
              const SizedBox(
                height: 40,
              ),
              const Text(
                'Converts amount with currencies codes.',
                style: style1,
              ),
              const SizedBox(
                height: 10,
              ),
              FutureBuilder<ConversionData?>(
                  future: geoCurrencies.convertAmountWithCurrenciesCodes(
                    amount: 10,
                    fromCurrencyCodeIso4217: 'EUR',
                    toCurrencyCodeIso4217: 'XAF',
                  ),
                  builder: (context, snapshot) {
                    return Column(
                      children: [
                        Text(
                          'amountConverted: ${snapshot.data?.amountConverted}',
                        ),
                        Text(
                          'baseAmount: ${snapshot.data?.baseAmount}',
                        ),
                        Text(
                          'formattedAmountConvertedWithCurrencyCode: ${snapshot.data?.formattedAmountConvertedWithCurrencyCode}',
                        ),
                        Text(
                          'formattedAmountConvertedWithCurrencySymbol: ${snapshot.data?.formattedAmountConvertedWithCurrencySymbol}',
                        ),
                        Text(
                          'toCurrencyCodeIso4217: ${snapshot.data?.toCurrencyCodeIso4217}',
                        ),
                      ],
                    );
                  }),
              const SizedBox(
                height: 40,
              ),
              const Text(
                'Gets rate.',
                style: style1,
              ),
              const SizedBox(
                height: 10,
              ),
              FutureBuilder<RateData?>(
                  future: geoCurrencies.getRate(
                    fromCurrencyCodeIso4217: 'EUR',
                    toCurrencyCodeIso4217: 'XAF',
                  ),
                  builder: (context, snapshot) {
                    return Column(
                      children: [
                        Text(
                          'fromCurrencyCodeIso4217: ${snapshot.data?.fromCurrencyCodeIso4217}',
                        ),
                        Text(
                          'rate: ${snapshot.data?.rate}',
                        ),
                        Text(
                          'toCurrencyCodeIso4217: ${snapshot.data?.toCurrencyCodeIso4217}',
                        ),
                      ],
                    );
                  }),
            ],
          ),
        ),
      ),
    );
  }
}

依赖项

pubspec.yaml 文件中添加以下依赖项:

dependencies:
  http: ^1.1.0
  intl: ^0.19.1
  logging: ^1.0.2

更多关于Flutter货币转换插件geo_currencies的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter货币转换插件geo_currencies的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用geo_currencies插件进行货币转换的代码示例。这个插件可以帮助你获取最新的货币汇率并进行转换。

首先,确保你已经在pubspec.yaml文件中添加了geo_currencies依赖:

dependencies:
  flutter:
    sdk: flutter
  geo_currencies: ^最新版本号  # 请替换为实际的最新版本号

然后,运行flutter pub get来安装依赖。

接下来,你可以在你的Flutter应用中使用以下代码进行货币转换:

import 'package:flutter/material.dart';
import 'package:geo_currencies/geo_currencies.dart';

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

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

class _MyAppState extends State<MyApp> {
  final GeoCurrencies _geoCurrencies = GeoCurrencies();
  String? fromCurrencyCode;
  String? toCurrencyCode;
  double? amount;
  double? convertedAmount;
  String? error;

  @override
  void initState() {
    super.initState();
    // 初始化一些默认货币代码(例如USD到EUR)
    fromCurrencyCode = 'USD';
    toCurrencyCode = 'EUR';
    amount = 100.0;
    _convertCurrency();
  }

  Future<void> _convertCurrency() async {
    setState(() {
      error = null;
      convertedAmount = null;
    });

    try {
      double rate = await _geoCurrencies.getExchangeRate(fromCurrencyCode!, toCurrencyCode!);
      convertedAmount = amount! * rate;
    } catch (e) {
      setState(() {
        error = e.toString();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Currency Converter'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              TextField(
                decoration: InputDecoration(labelText: 'From Currency Code'),
                keyboardType: TextInputType.text,
                onChanged: (value) {
                  setState(() {
                    fromCurrencyCode = value;
                  });
                  _convertCurrency();
                },
                controller: TextEditingController(text: fromCurrencyCode ?? ''),
              ),
              SizedBox(height: 16),
              TextField(
                decoration: InputDecoration(labelText: 'To Currency Code'),
                keyboardType: TextInputType.text,
                onChanged: (value) {
                  setState(() {
                    toCurrencyCode = value;
                  });
                  _convertCurrency();
                },
                controller: TextEditingController(text: toCurrencyCode ?? ''),
              ),
              SizedBox(height: 16),
              TextField(
                decoration: InputDecoration(labelText: 'Amount'),
                keyboardType: TextInputType.numberWithOptions(decimal: true),
                onChanged: (value) {
                  setState(() {
                    amount = double.tryParse(value) ?? 0.0;
                  });
                  _convertCurrency();
                },
                controller: TextEditingController(text: amount?.toString() ?? ''),
              ),
              SizedBox(height: 16),
              if (error != null)
                Text(
                  'Error: $error',
                  style: TextStyle(color: Colors.red),
                ),
              if (convertedAmount != null)
                Text(
                  '${amount?.toString()} ${fromCurrencyCode!} = ${convertedAmount?.toStringAsFixed(2)} ${toCurrencyCode!}',
                  style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
                ),
            ],
          ),
        ),
      ),
    );
  }
}

在这个示例中,我们创建了一个简单的Flutter应用,用户可以输入源货币代码、目标货币代码和金额,应用会实时显示转换后的金额。我们使用GeoCurrencies插件的getExchangeRate方法来获取汇率,并据此进行转换。

请注意,geo_currencies插件可能会依赖于外部API来获取最新的汇率数据,因此在实际应用中,你可能需要处理API调用失败的情况,并可能需要在UI中提供用户友好的错误提示。

回到顶部