Flutter票据打印插件flutter_gb_pos_print的使用

Flutter票据打印插件flutter_gb_pos_print的使用

flutter_gb_pos_print 插件可以帮助你在 Flutter 应用程序中实现票据打印功能。以下是如何使用该插件的详细说明和完整示例。

示例代码

example/lib/main.dart

import 'dart:convert';
import 'dart:typed_data';

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

import 'package:flutter/services.dart';
import 'package:flutter_gb_pos_print/flutter_gb_pos_print.dart';

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

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('插件示例应用'),
        ),
        body: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            MaterialButton(
              child: const Text(
                "测试打印",
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 20,
                ),
              ),
              onPressed: () async {
                // 要打印的文本内容
                String printText =
                    "GAZIBEL HIZ MUS INS SAN TIC A.S.\nHAYDI\n\n终端编号: 000111\n24.10.2022 17:02:10\n\n-------- 销售操作 --------\n\n操作编号 : 0069477\n确认编号 : 0000360\n金额     : 3,00 TL \n \r \n";
                // 要生成的二维码数据
                String? qrData = "ismailunal.net";

                // 使用 GBPosPrint 进行全内容打印
                await GBPosPrint.fullContent(
                  content: printText,
                  qrData: qrData,
                  footerLogo: true,
                  footerCode: "GBB",
                );
              },
              color: Colors.green,
            ),
          ],
        ),
      ),
    );
  }
}

代码解释

  1. 导入必要的库:

    import 'dart:convert';
    import 'dart:typed_data';
    
    import 'package:flutter/material.dart';
    import 'dart:async';
    
    import 'package:flutter/services.dart';
    import 'package:flutter_gb_pos_print/flutter_gb_pos_print.dart';
    
  2. 定义主应用程序类:

    void main() {
      runApp(const MyApp());
    }
    
    class MyApp extends StatefulWidget {
      const MyApp({Key? key}) : super(key: key);
    
      @override
      State<MyApp> createState() => _MyAppState();
    }
    
  3. 初始化状态并构建UI:

    class _MyAppState extends State<MyApp> {
      @override
      void initState() {
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: const Text('插件示例应用'),
            ),
            body: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                MaterialButton(
                  child: const Text(
                    "测试打印",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 20,
                    ),
                  ),
                  onPressed: () async {
                    // 要打印的文本内容
                    String printText =
                        "GAZIBEL HIZ MUS INS SAN TIC A.S.\nHAYDI\n\n终端编号: 000111\n24.10.2022 17:02:10\n\n-------- 销售操作 --------\n\n操作编号 : 0069477\n确认编号 : 0000360\n金额     : 3,00 TL \n \r \n";
                    // 要生成的二维码数据
                    String? qrData = "ismailunal.net";
    
                    // 使用 GBPosPrint 进行全内容打印
                    await GBPosPrint.fullContent(
                      content: printText,
                      qrData: qrData,
                      footerLogo: true,
                      footerCode: "GBB",
                    );
                  },
                  color: Colors.green,
                ),
              ],
            ),
          ),
        );
      }
    }
    

更多关于Flutter票据打印插件flutter_gb_pos_print的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter票据打印插件flutter_gb_pos_print的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


flutter_gb_pos_print 是一个用于 Flutter 的票据打印插件,它允许你通过蓝牙连接 POS 打印机并打印小票。这个插件通常用于餐饮、零售等需要打印小票的场景。

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 flutter_gb_pos_print 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_gb_pos_print: ^0.0.1  # 请检查最新版本

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

2. 初始化插件

在你的 Flutter 应用中,首先需要初始化插件并扫描可用设备:

import 'package:flutter_gb_pos_print/flutter_gb_pos_print.dart';

void initPrinter() async {
  // 初始化插件
  await FlutterGbPosPrint.init();

  // 扫描可用设备
  List<BluetoothDevice> devices = await FlutterGbPosPrint.scanDevices();
  
  // 打印设备列表
  devices.forEach((device) {
    print('Device: ${device.name}, Address: ${device.address}');
  });
}

3. 连接打印机

选择一个设备并连接:

void connectToPrinter(BluetoothDevice device) async {
  bool isConnected = await FlutterGbPosPrint.connect(device.address);
  
  if (isConnected) {
    print('Connected to ${device.name}');
  } else {
    print('Failed to connect to ${device.name}');
  }
}

4. 打印小票

连接成功后,你可以调用 print 方法来打印小票。通常你需要传递一个包含打印内容的字符串:

void printReceipt() async {
  String receipt = """
  === 餐厅小票 ===
  订单号: 123456
  时间: 2023-10-01 12:00
  -----------------
  商品        数量    价格
  汉堡        1       10.00
  薯条        1       5.00
  -----------------
  总计:       15.00
  === 谢谢惠顾 ===
  """;

  bool isPrinted = await FlutterGbPosPrint.print(receipt);
  
  if (isPrinted) {
    print('Receipt printed successfully');
  } else {
    print('Failed to print receipt');
  }
}

5. 断开连接

打印完成后,你可以断开与打印机的连接:

void disconnectPrinter() async {
  await FlutterGbPosPrint.disconnect();
  print('Disconnected from printer');
}

6. 完整示例

以下是一个完整的示例,展示了如何初始化插件、扫描设备、连接打印机并打印小票:

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: PrinterScreen(),
    );
  }
}

class PrinterScreen extends StatefulWidget {
  [@override](/user/override)
  _PrinterScreenState createState() => _PrinterScreenState();
}

class _PrinterScreenState extends State<PrinterScreen> {
  List<BluetoothDevice> devices = [];
  BluetoothDevice? selectedDevice;

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

  void initPrinter() async {
    await FlutterGbPosPrint.init();
    devices = await FlutterGbPosPrint.scanDevices();
    setState(() {});
  }

  void connectToPrinter(BluetoothDevice device) async {
    bool isConnected = await FlutterGbPosPrint.connect(device.address);
    if (isConnected) {
      setState(() {
        selectedDevice = device;
      });
      print('Connected to ${device.name}');
    } else {
      print('Failed to connect to ${device.name}');
    }
  }

  void printReceipt() async {
    String receipt = """
    === 餐厅小票 ===
    订单号: 123456
    时间: 2023-10-01 12:00
    -----------------
    商品        数量    价格
    汉堡        1       10.00
    薯条        1       5.00
    -----------------
    总计:       15.00
    === 谢谢惠顾 ===
    """;

    bool isPrinted = await FlutterGbPosPrint.print(receipt);
    if (isPrinted) {
      print('Receipt printed successfully');
    } else {
      print('Failed to print receipt');
    }
  }

  void disconnectPrinter() async {
    await FlutterGbPosPrint.disconnect();
    setState(() {
      selectedDevice = null;
    });
    print('Disconnected from printer');
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('POS Printer'),
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              itemCount: devices.length,
              itemBuilder: (context, index) {
                return ListTile(
                  title: Text(devices[index].name),
                  subtitle: Text(devices[index].address),
                  onTap: () => connectToPrinter(devices[index]),
                );
              },
            ),
          ),
          if (selectedDevice != null)
            Column(
              children: [
                Text('Connected to: ${selectedDevice!.name}'),
                ElevatedButton(
                  onPressed: printReceipt,
                  child: Text('Print Receipt'),
                ),
                ElevatedButton(
                  onPressed: disconnectPrinter,
                  child: Text('Disconnect'),
                ),
              ],
            ),
        ],
      ),
    );
  }
}
回到顶部