Flutter热敏打印机控制插件datecs_printer的使用

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

Flutter热敏打印机控制插件datecs_printer的使用

datecs_printer 是一个专门为Android平台设计的Flutter插件,用于控制热敏打印机。目前该插件不支持iOS、Web和桌面平台。

已报告可工作的打印机型号

以下型号已被报告为正常工作:

  • DATECS DPP 250
  • DATECS DPP 350
  • DATECS DPP 450
  • EPSON TM P80
  • Bixolon SPP-R210
  • MPT-3 (JP Printer)
  • MPT-III (LEOPARDO A7)
  • MPT-II (58mm)
  • DAPPER DP-HT201 58mm
  • RG-MTP80B
  • Black Copper MINI Thermal Printer BC-P58B
  • MHT-P5801 (58mm)

使用简单收据

Future<List<String>> getTicketDatecs({bool withImage}) async {
    final generate = DatecsGenerate(DatecsPaper.mm80);

    if (withImage) {
      ByteData bytes = await rootBundle.load('assets/empty-box.png');
      var buffer = bytes.buffer;
      var m = base64Encode(Uint8List.view(buffer));

      generate.image(m);
    }
    generate.feed(2);
    generate.textPrint("Demo Shop", style: DatecsStyle(
      bold: false,
      italic: false,
      underline: false,
      align: DatecsAlign.center,
      size: DatecsSize.high,
    ),);
    generate.textPrint(
        "18th Main Road, 2nd Phase, J. P. Nagar, Bengaluru, Karnataka 560078",
        style: DatecsStyle(align: DatecsAlign.center, bold: false,
          italic: false,
          underline: false,));
    generate.textPrint('Tel: +919591708470',
        style: DatecsStyle(align: DatecsAlign.center, bold: false,
          italic: false,
          underline: false,));

    generate.hr(char: "=");

    generate.row([
      DatecsColumn(
          text: 'No',
          width: 1,
          styles: DatecsStyle(align: DatecsAlign.left, bold: true)
      ),
      DatecsColumn(
          text: 'Item',
          width: 5,
          styles: DatecsStyle(align: DatecsAlign.left, bold: true)
      ),
      DatecsColumn(
          text: 'Price',
          width: 2,
          styles: DatecsStyle(align: DatecsAlign.center, bold: true)
      ),
      DatecsColumn(
          text: 'Qty',
          width: 2,
          styles: DatecsStyle(align: DatecsAlign.center, bold: true)
      ),
      DatecsColumn(
          text: 'Total',
          width: 2,
          styles: DatecsStyle(align: DatecsAlign.right, bold: true)
      ),
    ]);
    generate.hr();
    generate.row([
      DatecsColumn(
          text: '1',
          width: 1,
          styles: DatecsStyle(align: DatecsAlign.left, bold: true)
      ),
      DatecsColumn(
          text: 'Tea',
          width: 5,
          styles: DatecsStyle(align: DatecsAlign.left, bold: true)
      ),
      DatecsColumn(
          text: '10',
          width: 2,
          styles: DatecsStyle(align: DatecsAlign.center, bold: true)
      ),
      DatecsColumn(
          text: '1',
          width: 2,
          styles: DatecsStyle(align: DatecsAlign.center, bold: true)
      ),
      DatecsColumn(
          text: '10',
          width: 2,
          styles: DatecsStyle(align: DatecsAlign.right, bold: true)
      ),
    ]);

    generate.row([
      DatecsColumn(
          text: '2',
          width: 1,
          styles: DatecsStyle(align: DatecsAlign.left, bold: true)
      ),
      DatecsColumn(
          text: 'Sada Dosa',
          width: 5,
          styles: DatecsStyle(align: DatecsAlign.left, bold: true)
      ),
      DatecsColumn(
          text: '30',
          width: 2,
          styles: DatecsStyle(align: DatecsAlign.center, bold: true)
      ),
      DatecsColumn(
          text: '1',
          width: 2,
          styles: DatecsStyle(align: DatecsAlign.center, bold: true)
      ),
      DatecsColumn(
          text: '30',
          width: 2,
          styles: DatecsStyle(align: DatecsAlign.right, bold: true)
      ),
    ]);
    generate.feed(5);

    return generate.args;
}

打印收据

List<String> ticket = await getTicketDatecs(withImage: true);
var result = await DatecsPrinter.printText(ticket);

完整示例代码

以下是完整的示例代码,展示了如何使用 datecs_printer 插件进行热敏打印:

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

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

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

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

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

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

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  List availableBluetoothDevices = [];
  DatecsDevice? _device;
  bool connected = false;

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

  // 平台消息是异步的,因此我们在异步方法中初始化。
  Future<void> initPlatformState() async {
    String platformVersion;
    // 平台消息可能会失败,所以我们使用 try/catch PlatformException。
    // 我们还处理了消息可能返回null的情况。
    try {
      platformVersion = await DatecsPrinter.platformVersion ?? 'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // 如果小部件在异步平台消息仍在飞行时从树中移除,我们想要丢弃回复而不是调用
    // setState 来更新我们的不存在的外观。
    if (!mounted) return;

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

  Future<List<String>> getTicketDatecs({bool withImage = false}) async {
    final generate = DatecsGenerate(DatecsPaper.mm80);

    if (withImage) {
      ByteData bytes = await rootBundle.load('assets/empty-box.png');
      var buffer = bytes.buffer;
      var m = base64Encode(Uint8List.view(buffer));

      generate.image(m);
    }
    generate.feed(2);
    generate.textPrint("Demo Shop", style: DatecsStyle(
      bold: false,
      italic: false,
      underline: false,
      align: DatecsAlign.center,
      size: DatecsSize.high,
    ),);
    generate.textPrint(
        "18th Main Road, 2nd Phase, J. P. Nagar, Bengaluru, Karnataka 560078",
        style: DatecsStyle(align: DatecsAlign.center, bold: false,
          italic: false,
          underline: false,));
    generate.textPrint('Tel: +919591708470',
        style: DatecsStyle(align: DatecsAlign.center, bold: false,
          italic: false,
          underline: false,));

    generate.hr(char: "=");

    generate.row([
      DatecsColumn(
          text: 'No',
          width: 1,
          styles: DatecsStyle(align: DatecsAlign.left, bold: true)
      ),
      DatecsColumn(
          text: 'Item',
          width: 5,
          styles: DatecsStyle(align: DatecsAlign.left, bold: true)
      ),
      DatecsColumn(
          text: 'Price',
          width: 2,
          styles: DatecsStyle(align: DatecsAlign.center, bold: true)
      ),
      DatecsColumn(
          text: 'Qty',
          width: 2,
          styles: DatecsStyle(align: DatecsAlign.center, bold: true)
      ),
      DatecsColumn(
          text: 'Total',
          width: 2,
          styles: DatecsStyle(align: DatecsAlign.right, bold: true)
      ),
    ]);
    generate.hr();
    generate.row([
      DatecsColumn(
          text: '1',
          width: 1,
          styles: DatecsStyle(align: DatecsAlign.left, bold: true)
      ),
      DatecsColumn(
          text: 'Tea',
          width: 5,
          styles: DatecsStyle(align: DatecsAlign.left, bold: true)
      ),
      DatecsColumn(
          text: '10',
          width: 2,
          styles: DatecsStyle(align: DatecsAlign.center, bold: true)
      ),
      DatecsColumn(
          text: '1',
          width: 2,
          styles: DatecsStyle(align: DatecsAlign.center, bold: true)
      ),
      DatecsColumn(
          text: '10',
          width: 2,
          styles: DatecsStyle(align: DatecsAlign.right, bold: true)
      ),
    ]);

    generate.row([
      DatecsColumn(
          text: '2',
          width: 1,
          styles: DatecsStyle(align: DatecsAlign.left, bold: true)
      ),
      DatecsColumn(
          text: 'Sada Dosa',
          width: 5,
          styles: DatecsStyle(align: DatecsAlign.left, bold: true)
      ),
      DatecsColumn(
          text: '30',
          width: 2,
          styles: DatecsStyle(align: DatecsAlign.center, bold: true)
      ),
      DatecsColumn(
          text: '1',
          width: 2,
          styles: DatecsStyle(align: DatecsAlign.center, bold: true)
      ),
      DatecsColumn(
          text: '30',
          width: 2,
          styles: DatecsStyle(align: DatecsAlign.right, bold: true)
      ),
    ]);
    generate.feed(5);

    return generate.args;
  }

  _getListBluetooth() async {
    List<dynamic> list = await DatecsPrinter.getListBluetoothDevice;
    List<DatecsDevice> listOfDevice = [];
    for (var element in list) {
      var bluetooth = element as Map<dynamic, dynamic>;
      var name, address;
      bluetooth.forEach((key, value) {
        key == "name" ? name = value : address = value;
      });
      listOfDevice.add(DatecsDevice(name, address));
    }
    setState(() {
      availableBluetoothDevices = listOfDevice;
    });
  }

  List<DropdownMenuItem<DatecsDevice>> _getDeviceItems() {
    List<DropdownMenuItem<DatecsDevice>> items = [];
    if (availableBluetoothDevices.isEmpty) {
      items.add(const DropdownMenuItem(
        child: Text('NONE'),
      ));
    } else {
      for (var device in availableBluetoothDevices) {
        items.add(DropdownMenuItem(
          child: Text(device.name, overflow: TextOverflow.ellipsis),
          value: DatecsDevice(device.name, device.address),
        ));
      }
    }

    return items;
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin Datecs app'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(12.0),
          child: Column(
            children: [
              const SizedBox(height: 20,),
              Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  const Text(
                    'Device:',
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(width: 30,),
                  Expanded(
                    child: DropdownButton(
                      isExpanded: true,
                      items: _getDeviceItems(),
                      onChanged: (value) async {
                        setState(() {
                          _device = value as DatecsDevice;
                        });
                      }, //_disconnect
                      value: _device,
                    ),
                  ),
                  const SizedBox(width: 10,),
                  IconButton(
                    color: Theme.of(context).primaryColor,
                    icon: const Icon(Icons.refresh),
                    onPressed: () async {
                      _getListBluetooth();
                    },
                  ),
                ],
              ),
              const SizedBox(height: 20,),
              FlatButton(
                color: Theme.of(context).primaryColor,
                onPressed: () async {
                  if (_device == null) {
                    Fluttertoast.showToast(msg: "Device not selected");
                    return;
                  }
                  try {
                    var result = await DatecsPrinter.connectBluetooth(_device!.address);
                    if (result) {
                      Fluttertoast.showToast(msg: "Device connected");
                    }
                  } catch (e) {
                    Fluttertoast.showToast(msg: e.toString());
                  }
                },
                child: const Text(
                  'Connect',
                  style: TextStyle(color: Colors.white),
                ),
              ),
              const SizedBox(height: 20,),
              RawMaterialButton(
                fillColor: Colors.blue,
                onPressed: () async {
                  List<String> ticket = await getTicketDatecs(withImage: false);
                  var result = await DatecsPrinter.printText(ticket);
                },
                child: const Padding(
                  padding: EdgeInsets.all(8),
                  child: Text(
                    'Test Print ',
                    style: TextStyle(
                      color: Colors.white
                    ),
                  ),
                )
              ),
              const SizedBox(height: 20,),
              RawMaterialButton(
                fillColor: Colors.blue,
                onPressed: () async {
                  List<String> ticket = await getTicketDatecs(withImage: true);
                  var result = await DatecsPrinter.printText(ticket);
                },
                child: const Padding(
                  padding: EdgeInsets.all(8),
                  child: Text(
                    'Test Print with Image',
                    style: TextStyle(
                      color: Colors.white
                    ),
                  ),
                )
              ),
              const SizedBox(height: 20,),
              RawMaterialButton(
                fillColor: Colors.blue,
                onPressed: () async {
                  await DatecsPrinter.printTest;
                },
                child: const Padding(
                  padding: EdgeInsets.all(8),
                  child: Text(
                    'Test Print with Default Machine',
                    style: TextStyle(
                      color: Colors.white
                    ),
                  ),
                )
              ),
            ],
          ),
        )
      ),
    );
  }
}

更多关于Flutter热敏打印机控制插件datecs_printer的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter热敏打印机控制插件datecs_printer的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用datecs_printer插件来控制Datecs热敏打印机的示例代码。这个插件允许你通过Flutter应用直接发送打印命令到支持的热敏打印机。

首先,确保你的Flutter项目已经添加了对datecs_printer插件的依赖。你可以在pubspec.yaml文件中添加以下依赖项:

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

然后运行flutter pub get来安装插件。

接下来,你可以在Flutter项目中创建一个新的Dart文件来管理打印机的连接和打印任务。以下是一个示例代码,展示了如何初始化打印机、发送打印命令以及处理错误。

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Datecs Printer Example'),
        ),
        body: Center(
          child: PrinterControl(),
        ),
      ),
    );
  }
}

class PrinterControl extends StatefulWidget {
  @override
  _PrinterControlState createState() => _PrinterControlState();
}

class _PrinterControlState extends State<PrinterControl> {
  late DatecsPrinter _printer;
  late String _statusText = "Not Connected";

  @override
  void initState() {
    super.initState();
    _printer = DatecsPrinter.instance;

    // 监听打印机状态变化
    _printer.printerStatusStream.listen((status) {
      setState(() {
        _statusText = status;
      });
    });

    // 初始化打印机连接(假设使用蓝牙连接)
    _initializePrinter();
  }

  Future<void> _initializePrinter() async {
    try {
      // 替换为你的打印机名称或地址
      await _printer.connect("Datecs-Printer-Name");
      setState(() {
        _statusText = "Connected";
      });
    } catch (e) {
      setState(() {
        _statusText = "Failed to connect: ${e.message}";
      });
    }
  }

  Future<void> _printText() async {
    try {
      // 打印文本
      await _printer.sendText("Hello, Datecs Printer!\n");
      await _printer.sendText("This is a test print.\n");
      await _printer.newLine();
      await _printer.cutPaper();
      
      setState(() {
        _statusText = "Print Successful";
      });
    } catch (e) {
      setState(() {
        _statusText = "Print Failed: ${e.message}";
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Text("Printer Status: $_statusText"),
        SizedBox(height: 20),
        ElevatedButton(
          onPressed: _printText,
          child: Text("Print Text"),
        ),
      ],
    );
  }

  @override
  void dispose() {
    // 断开打印机连接
    _printer.disconnect();
    super.dispose();
  }
}

说明:

  1. 依赖安装:确保datecs_printer插件已经正确添加到pubspec.yaml中,并运行flutter pub get
  2. 打印机连接:在_initializePrinter方法中,替换"Datecs-Printer-Name"为你的打印机名称或地址。这里假设使用蓝牙连接,根据实际情况可能需要修改连接方法(如USB、网络等)。
  3. 打印命令:在_printText方法中,使用_printer.sendText发送打印文本,使用_printer.newLine换行,使用_printer.cutPaper切纸。
  4. 状态管理:使用Flutter的状态管理(setState)来更新UI以反映打印机的状态。
  5. 断开连接:在dispose方法中,确保在组件销毁时断开打印机连接。

请根据你的实际需求和打印机型号调整代码。如果你使用的是其他类型的连接(如USB、网络等),请查阅datecs_printer插件的文档以获取相应的连接方法。

回到顶部