Flutter巴西银行集成插件brazilian_banks的使用

发布于 1周前 作者 phonegap100 来自 Flutter

Flutter巴西银行集成插件brazilian_banks的使用

简介

brazilian_banks是一个Flutter插件,提供了巴西银行列表以及账户和数字验证的功能。本文将介绍如何使用该插件来获取银行信息并进行相关验证。

开始使用

首先,在项目中导入brazilian_banks包:

import 'package:brazilian_banks/brazilian_banks.dart';

获取巴西银行列表

可以通过以下代码获取所有支持的巴西银行列表:

final banks = await BrasilApiBanks.getBanks();

验证巴西银行账号数字

当前支持的银行有:

  • Banco do Brasil (001)
  • Bradesco (237)
  • CEF - Caixa Econômica Federal (104)
  • Itau (341)

示例代码如下:

var response = BankAccountValidationService().validateAccountNumber(
    bankAccountModel: BankAccountModel(
        bankCode: 341, // 示例:Itau银行
        branchNumber: '2545',
        accountNumberWithDigit: '02366-1',
        accountType: AccountType.checking),
);

if (response.errorMessage == null) {
    if (response.isValid) {
        print('account digit is correct');
    } else {
        print('the correct account digit probably is ${response.digit}');
    }
} else {
    print(response.errorMessage);
}

验证巴西银行支行数字

当前支持的银行有:

  • Banco do Brasil (001)
  • Bradesco (237)

示例代码如下:

final response = BankBranchValidationService().validateBranchNumber(
        bankBranchModel: BankBranchModel(
          bankCode: bankCode,
          branchNumber: text,
        ),
      );

使用格式化器对账户和支行进行格式化

支持的银行包括:

  • Banco do Brasil (001)
  • Bradesco (237)
  • CEF - Caixa Econômica Federal (104)
  • Itau (341)

在输入字段中使用格式化器:

inputFormatters: [
    AccountInputFormatter(bankCode: bankCode, accountType: accountType)
],

inputFormatters: [BranchInputFormatter(bankCode: bankCode)],

使用已经带有验证和格式化的控件

可以直接使用预设好的控件,它们已经包含了验证和格式化功能:

BankBranchTextFormField(
    decoration: const InputDecoration(label: Text("Agência")),
    bankCode: int.tryParse(_bankTextController.text) ?? 000,
    controller: _branchTextController,
    invalidInputsMenssage: 'Informe valores válidos',
    incorrectBranchDigitMenssage: 'Dígito da agência errado, não seria {}?',
),

BankAccountTextFormField(
    decoration: const InputDecoration(label: Text("Conta")),
    bankCode: int.tryParse(_bankTextController.text) ?? 000,
    accountType: AccountType.checking,
    controller: _accountTextController,
    branchNumber: _branchTextController.text,
    invalidInputsMenssage: 'Informe valores válidos',
    incorrectAccountDigitMenssage: 'Dígito da conta errado, não seria {}?',
),

完整示例Demo

以下是完整的示例代码,展示了如何在Flutter应用中集成并使用brazilian_banks插件:

import 'package:flutter/material.dart';
import 'package:brazilian_banks/brazilian_banks.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: 'Brazilian Banks Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const HomePage(title: 'Brazilian Banks Package'),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final TextEditingController _bankTextController = TextEditingController();
  final TextEditingController _branchTextController = TextEditingController();
  final TextEditingController _accountTextController = TextEditingController();

  void _validateAccount() async {
    var response = BankAccountValidationService().validateAccountNumber(
      bankAccountModel: BankAccountModel(
        bankCode: 341, // 示例:Itau银行
        branchNumber: _branchTextController.text,
        accountNumberWithDigit: _accountTextController.text,
        accountType: AccountType.checking,
      ),
    );

    if (response.errorMessage == null) {
      if (response.isValid) {
        ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('account digit is correct')));
      } else {
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(
            content:
                Text('the correct account digit probably is ${response.digit}')));
      }
    } else {
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text(response.errorMessage!)));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: <Widget>[
            TextField(
              controller: _bankTextController,
              decoration: const InputDecoration(labelText: 'Bank Code'),
            ),
            TextField(
              controller: _branchTextController,
              decoration: const InputDecoration(labelText: 'Branch Number'),
            ),
            TextField(
              controller: _accountTextController,
              decoration: const InputDecoration(labelText: 'Account Number with Digit'),
            ),
            ElevatedButton(
              onPressed: _validateAccount,
              child: const Text('Validate Account'),
            ),
          ],
        ),
      ),
    );
  }
}

通过上述示例,您可以轻松地在Flutter应用程序中集成并使用brazilian_banks插件来进行银行信息的查询和验证。


更多关于Flutter巴西银行集成插件brazilian_banks的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter巴西银行集成插件brazilian_banks的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter应用中集成并使用brazilian_banks插件来处理巴西银行相关功能的示例代码。brazilian_banks插件通常用于验证巴西银行账户信息、生成Pix键等。

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

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

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

接下来,在你的Flutter应用中,你可以按照以下步骤使用brazilian_banks插件:

1. 导入插件

在你的Dart文件中导入插件:

import 'package:brazilian_banks/brazilian_banks.dart';

2. 验证银行账户信息

你可以使用validateBankAccount方法来验证巴西银行账户信息。例如:

void validateBankAccountExample() async {
  String agency = '1234';
  String account = '56789';
  String accountType = 'CC'; // or 'CP' for checking account
  String bankCode = '341'; // Banco Itaú's code

  try {
    BankAccountValidationResult result = await BrazilianBanks.validateBankAccount(
      agency: agency,
      account: account,
      accountType: accountType,
      bankCode: bankCode,
    );

    if (result.isValid) {
      print('Bank account is valid.');
    } else {
      print('Bank account is invalid.');
    }
  } catch (e) {
    print('Error validating bank account: $e');
  }
}

3. 生成Pix键

使用generatePixKey方法可以生成一个Pix键。例如:

void generatePixKeyExample() async {
  String cpfOrCnpj = '12345678901'; // CPF or CNPJ
  String keyType = 'CPF'; // or 'CNPJ' or 'RANDOM'

  try {
    PixKeyResult result = await BrazilianBanks.generatePixKey(
      cpfOrCnpj: cpfOrCnpj,
      keyType: keyType,
    );

    print('Generated Pix Key: ${result.pixKey}');
  } catch (e) {
    print('Error generating Pix Key: $e');
  }
}

4. 在UI中使用

你可以将这些功能集成到你的Flutter应用的UI中。例如,使用按钮触发验证和生成Pix键的操作:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Brazilian Banks Example',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Brazilian Banks Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              ElevatedButton(
                onPressed: validateBankAccountExample,
                child: Text('Validate Bank Account'),
              ),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: generatePixKeyExample,
                child: Text('Generate Pix Key'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

void validateBankAccountExample() async {
  // 同上示例代码
}

void generatePixKeyExample() async {
  // 同上示例代码
}

这个示例展示了如何在Flutter应用中集成brazilian_banks插件,并通过UI按钮触发银行账户验证和Pix键生成功能。你可以根据实际需求进一步定制和扩展这些功能。

回到顶部