Flutter设备连接管理插件fl_droid_connection的使用

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

Flutter设备连接管理插件fl_droid_connection的使用

平台支持

Android
✔️

安装

pubspec.yaml 文件中添加依赖:

dependencies:
  fl_droid_connection: ^0.0.3

导入

在 Dart 文件中导入插件:

import 'package:fl_droid_connection/fl_droid_connection.dart';

使用/示例

函数

  import 'package:fl_droid_connection/fl_droid_connection.dart';

  // 获取平台版本信息
  getPlatformVersion();

  // ping
  ping();

  // 最后一次交易记录
  lastTransaction();

  // 结算
  settlement();

  // 传递Mpm请求
  passMpm(String request);

  // 传递Cpm请求
  passCpm(String request);

  // 销售操作 & 传递Mpm请求
  sale(String request);

  // 取消操作
  voidOperation(String request);

示例

以下是一个完整的示例,展示了如何使用 fl_droid_connection 插件。

import 'dart:convert';

import 'package:fl_droid_connection_example/classes/fl_droid_connection_request.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:fl_droid_connection/fl_droid_connection.dart';
import 'package:flutter/widgets.dart';

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

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

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  String _dynamicResult = 'Unknown';

  final _flDroidConnectionPlugin = FlDroidConnection();

  final TextEditingController _amountController = TextEditingController();
  final TextEditingController _amountPassMpmController = TextEditingController();
  final TextEditingController _amountPassCpmController = TextEditingController();
  final TextEditingController _paymentTokenController = TextEditingController();

  late BuildContext _buildContext;

  final List<Map<String, dynamic>> _transactions = [];

  [@override](/user/override)
  void initState() {
    super.initState();
    initPlatformState();
  }

  // 初始化平台状态
  Future<void> initPlatformState() async {
    String platformVersion;
    try {
      platformVersion = await _flDroidConnectionPlugin.getPlatformVersion() ?? 'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  // 发送ping请求
  Future<void> ping() async {
    String pingResult;
    try {
      pingResult = await _flDroidConnectionPlugin.ping() ?? 'Unkown ping result';
    } on PlatformException {
      pingResult = 'Failed to ping.';
    }

    if (!mounted) return;

    debugPrint(pingResult);
    setState(() {
      _dynamicResult = pingResult;
    });
  }

  // 获取最后一次交易记录
  Future<void> lastTransaction() async {
    String lastTransactionResult;
    try {
      lastTransactionResult = await _flDroidConnectionPlugin.lastTransaction() ?? 'Unkown lastTransaction result';
    } on PlatformException {
      lastTransactionResult = 'Failed to lastTransaction.';
    }

    if (!mounted) return;

    debugPrint(lastTransactionResult);
    setState(() {
      _dynamicResult = lastTransactionResult;
    });
  }

  // 结算操作
  Future<void> settlement() async {
    String settlementResult;
    try {
      settlementResult = await _flDroidConnectionPlugin.settlement() ?? 'Unkown settlement result';
    } on PlatformException {
      settlementResult = 'Failed to settlement.';
    }

    if (!mounted) return;

    debugPrint(settlementResult);
    setState(() {
      _dynamicResult = settlementResult;
    });
  }

  // 传递Mpm请求
  Future<void> passMpm() async {
    String passMpmResult;
    try {
      passMpmResult = await _flDroidConnectionPlugin.passMpm(FlDroidConnectionRequest(amount: _amountPassMpmController.text).toRawJson()) ?? 'Unkown passMpm result';
    } on PlatformException {
      passMpmResult = 'Failed to passMpm.';
    }

    if (!mounted) return;

    debugPrint(passMpmResult);
    setState(() {
      _dynamicResult = passMpmResult;
    });
  }

  // 传递Cpm请求
  Future<void> passCpm() async {
    String passCpmResult;
    try {
      passCpmResult = await _flDroidConnectionPlugin.passCpm(FlDroidConnectionRequest(amount: _amountPassCpmController.text, paymentToken: _paymentTokenController.text).toRawJson()) ?? 'Unkown passCpm result';
    } on PlatformException {
      passCpmResult = 'Failed to passCpm.';
    }

    if (!mounted) return;

    debugPrint(passCpmResult);
    setState(() {
      _dynamicResult = passCpmResult;
    });
  }

  // 销售操作
  Future<void> sale() async {
    String saleResult;
    try {
      saleResult = await _flDroidConnectionPlugin.sale(FlDroidConnectionRequest(amount: _amountController.text).toRawJson()) ?? 'Unkown sale result';
    } on PlatformException {
      saleResult = 'Failed to sale.';
    }

    if (!mounted) return;

    Navigator.of(_buildContext, rootNavigator: true).pop();

    Map<String, dynamic> jsonResult = jsonDecode(saleResult);
    debugPrint(jsonResult.toString());
    debugPrint(saleResult);
    setState(() {
      _dynamicResult = saleResult;
      _transactions.add(jsonResult);
    });
  }

  // 取消操作
  Future<void> voidOperation(String traceNo) async {
    String voidResult;
    try {
      voidResult = await _flDroidConnectionPlugin.voidOperation(FlDroidConnectionRequest(traceNo: traceNo).toRawJson()) ?? 'Unkown void result';
    } on PlatformException {
      voidResult = 'Failed to void.';
    }

    if (!mounted) return;

    Map<String, dynamic> jsonResult = jsonDecode(voidResult);
    debugPrint(jsonResult.toString());
    debugPrint(voidResult);
    setState(() {
      _dynamicResult = voidResult;
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      localizationsDelegates: const [
        DefaultMaterialLocalizations.delegate,
        DefaultWidgetsLocalizations.delegate,
        DefaultCupertinoLocalizations.delegate,
      ],
      supportedLocales: const [
        Locale('en', ''),
        Locale('he', ''),
        Locale.fromSubtags(languageCode: 'zh')
      ],
      home: Builder(builder: (context) {
        _buildContext = context;
        return Scaffold(
          appBar: AppBar(
            title: const Text('Fl Droid Connection 包示例'),
          ),
          body: Row(
            children: [
              Expanded(
                  flex: 2,
                  child: Wrap(
                    spacing: 20,
                    alignment: WrapAlignment.start,
                    runAlignment: WrapAlignment.center,
                    crossAxisAlignment: WrapCrossAlignment.start,
                    direction: Axis.vertical,
                    children: [
                      ElevatedButton(
                          onPressed: () {
                            ping();
                          },
                          child: const Text('Ping')),
                      ElevatedButton(
                          onPressed: () {
                            lastTransaction();
                          },
                          child: const Text('最后一次交易')),
                      ElevatedButton(
                          onPressed: () {
                            settlement();
                          },
                          child: const Text('结算')),
                      ElevatedButton(
                          onPressed: () {
                            showDialog(
                                context: context,
                                builder: (_) {
                                  return AlertDialog(
                                    title: const Text('输入金额'),
                                    content: TextFormField(
                                      controller: _amountController,
                                    ),
                                    actions: [
                                      ElevatedButton(
                                          onPressed: () {
                                            if (_amountController.text.isEmpty || _amountController.text == "0") {
                                              return;
                                            }

                                            sale();
                                          },
                                          child: const Text('销售')),
                                    ],
                                  );
                                });
                          },
                          child: const Text('销售')),
                      ElevatedButton(
                          onPressed: () {
                            showDialog(
                                context: context,
                                builder: (_) {
                                  return AlertDialog(
                                    title: const Text('输入金额'),
                                    content: TextFormField(
                                      controller: _amountPassMpmController,
                                    ),
                                    actions: [
                                      ElevatedButton(
                                          onPressed: () {
                                            if (_amountPassMpmController.text.isEmpty || _amountPassMpmController.text == "0") {
                                              return;
                                            }

                                            passMpm();
                                          },
                                          child: const Text('Mpm销售')),
                                    ],
                                  );
                                });
                          },
                          child: const Text('Mpm销售')),
                      ElevatedButton(
                          onPressed: () {
                            showDialog(
                                context: context,
                                builder: (_) {
                                  return AlertDialog(
                                    title: const Text('输入金额 & 支付令牌'),
                                    content: Column(
                                      mainAxisSize: MainAxisSize.min,
                                      children: [
                                        TextFormField(
                                          controller: _amountPassCpmController,
                                          decoration: const InputDecoration(hintText: "金额"),
                                        ),
                                        TextFormField(
                                          controller: _paymentTokenController,
                                          decoration: const InputDecoration(hintText: "支付令牌"),
                                        ),
                                      ],
                                    ),
                                    actions: [
                                      ElevatedButton(
                                          onPressed: () {
                                            if (_amountPassCpmController.text.isEmpty || _amountPassCpmController.text == "0") {
                                              return;
                                            }

                                            if (_paymentTokenController.text.isEmpty) {
                                              return;
                                            }

                                            passCpm();
                                          },
                                          child: const Text('Cpm销售')),
                                    ],
                                  );
                                });
                          },
                          child: const Text('Cpm销售')),
                    ],
                  )),
              Expanded(
                  flex: 3,
                  child: Container(
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(15),
                        color: Colors.grey),
                    margin: const EdgeInsets.all(10),
                    padding: const EdgeInsets.all(10),
                    child: Column(
                      children: [
                        const Text(
                          "交易记录",
                          style: TextStyle(
                              color: Colors.black,
                              fontWeight: FontWeight.bold,
                              fontSize: 24),
                        ),
                        Expanded(
                          child: Visibility(
                            visible: _transactions.isNotEmpty,
                            replacement: const Text("无交易记录"),
                            child: ListView(
                              scrollDirection: Axis.vertical,
                              children: [
                                ..._transactions.map((e) {
                                  return ListTile(
                                    title: Text((e["status_code"] ?? "失败") + " : " + (e["ret"]?["response_code"] ?? "无")),
                                    subtitle: Text(e["ret"]?["amount"] ?? "无"),
                                    leading: Text(e["ret"]?["operation"] ?? "无"),
                                    trailing: Visibility(
                                      visible: e["status_code"] == "ok" && e["ret"]?["response_code"] == "000",
                                      child: ElevatedButton(
                                          onPressed: () {
                                            voidOperation(e["ret"]?["trace_no"] ?? "");
                                          },
                                          child: const Text("取消")),
                                    ),
                                  );
                                })
                              ],
                            ),
                          ),
                        )
                      ],
                    ),
                  )),
              Expanded(
                  flex: 3,
                  child: Container(
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(15),
                        color: Colors.grey),
                    margin: const EdgeInsets.all(10),
                    padding: const EdgeInsets.all(10),
                    child: Column(
                      children: [
                        const Text(
                          "响应",
                          style: TextStyle(
                              color: Colors.black,
                              fontWeight: FontWeight.bold,
                              fontSize: 24),
                        ),
                        Text(_dynamicResult)
                      ],
                    ),
                  ))
            ],
          ),
          bottomNavigationBar: Text('运行于: $_platformVersion\n'),
        );
      }),
    );
  }
}

更多关于Flutter设备连接管理插件fl_droid_connection的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter设备连接管理插件fl_droid_connection的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何使用 fl_droid_connection 插件来进行Flutter设备连接管理的示例代码。请注意,由于这是一个假设的插件名称,具体API和实现细节可能会有所不同。因此,以下代码是一个概念性的示例,旨在展示如何使用此类插件进行设备连接管理。

首先,确保你已经在 pubspec.yaml 文件中添加了 fl_droid_connection 插件的依赖项(假设它存在):

dependencies:
  flutter:
    sdk: flutter
  fl_droid_connection: ^x.y.z  # 替换为实际版本号

然后,运行 flutter pub get 来获取依赖项。

接下来,在你的 Flutter 应用中使用该插件。以下是一个简单的示例,展示如何初始化插件、检查设备连接状态以及管理连接。

import 'package:flutter/material.dart';
import 'package:fl_droid_connection/fl_droid_connection.dart';  // 假设的导入路径

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

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

class _MyAppState extends State<MyApp> {
  FlDroidConnection? _connectionManager;
  bool _isConnected = false;

  @override
  void initState() {
    super.initState();
    // 初始化插件
    _connectionManager = FlDroidConnection();

    // 监听连接状态变化
    _connectionManager!.connectionStatusStream!.listen((status) {
      setState(() {
        _isConnected = status == ConnectionStatus.connected;
      });
    });

    // 检查初始连接状态
    _checkConnection();
  }

  @override
  void dispose() {
    // 取消订阅
    _connectionManager!.connectionStatusStream!.cancel();
    super.dispose();
  }

  Future<void> _checkConnection() async {
    bool isConnected = await _connectionManager!.isConnected();
    setState(() {
      _isConnected = isConnected;
    });
  }

  Future<void> _toggleConnection() async {
    if (_isConnected) {
      await _connectionManager!.disconnect();
    } else {
      await _connectionManager!.connect();
    }

    // 重新检查连接状态
    _checkConnection();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Device Connection Management'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                'Device is $_isConnected',
                style: TextStyle(fontSize: 24),
              ),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: _toggleConnection,
                child: Text(
                  _isConnected ? 'Disconnect' : 'Connect',
                  style: TextStyle(fontSize: 20),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

在这个示例中:

  1. 我们首先导入了 fl_droid_connection 插件。
  2. MyAppinitState 方法中,我们初始化了 FlDroidConnection 实例,并订阅了连接状态流以监听连接状态的变化。
  3. 我们定义了一个 _checkConnection 方法来检查当前的连接状态,并在初始时调用它。
  4. _toggleConnection 方法用于切换设备的连接状态(连接或断开连接),并在操作后重新检查连接状态。
  5. 在UI中,我们显示当前的连接状态,并提供一个按钮来切换连接状态。

请注意,由于 fl_droid_connection 是一个假设的插件名称,因此上述代码中的API调用(如 isConnected(), connect(), disconnect(), 和 connectionStatusStream)可能需要根据实际插件的API进行调整。务必查阅该插件的官方文档以获取准确的API信息。

回到顶部