0
 import 'dart:io';
import 'dart:typed_data';
import 'package:blue_thermal_printer_example/testprint.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:blue_thermal_printer/blue_thermal_printer.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';

void main() => runApp(new MyApp());

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

class _MyAppState extends State<MyApp> {
 BlueThermalPrinter bluetooth = BlueThermalPrinter.instance;

 List<BluetoothDevice> _devices = [];
 BluetoothDevice _device;
 bool _connected = false;
 String pathImage;
 TestPrint testPrint;

 @override
 void initState() {
   super.initState();
   initPlatformState();
   initSavetoPath();
   testPrint = TestPrint();
 }

 initSavetoPath() async {
   //read and write
   //image max 300px X 300px
   final filename = 'yourlogo.png';
   var bytes = await rootBundle.load("assets/images/yourlogo.png");
   String dir = (await getApplicationDocumentsDirectory()).path;
   writeToFile(bytes, '$dir/$filename');
   setState(() {
     pathImage = '$dir/$filename';
   });
 }

 Future<void> initPlatformState() async {
   bool isConnected = await bluetooth.isConnected;
   List<BluetoothDevice> devices = [];
   try {
     devices = await bluetooth.getBondedDevices();
   } on PlatformException {
     // TODO - Error
   }

   bluetooth.onStateChanged().listen((state) {
     switch (state) {
       case BlueThermalPrinter.CONNECTED:
         setState(() {
           _connected = true;
         });
         break;
       case BlueThermalPrinter.DISCONNECTED:
         setState(() {
           _connected = false;
         });
         break;
       default:
         print(state);
         break;
     }
   });

   if (!mounted) return;
   setState(() {
     _devices = devices;
   });

   if (isConnected) {
     setState(() {
       _connected = true;
     });
   }
 }

 @override
 Widget build(BuildContext context) {
   return MaterialApp(
     home: Scaffold(
       appBar: AppBar(
         title: Text('Blue Thermal Printer'),
       ),
       body: Container(
         child: Padding(
           padding: const EdgeInsets.all(8.0),
           child: ListView(
             children: <Widget>[
               Row(
                 crossAxisAlignment: CrossAxisAlignment.center,
                 mainAxisAlignment: MainAxisAlignment.start,
                 children: <Widget>[
                   SizedBox(
                     width: 10,
                   ),
                   Text(
                     'Device:',
                     style: TextStyle(
                       fontWeight: FontWeight.bold,
                     ),
                   ),
                   SizedBox(
                     width: 30,
                   ),
                   Expanded(
                     child: DropdownButton(
                       items: _getDeviceItems(),
                       onChanged: (value) => setState(() => _device = value),
                       value: _device,
                     ),
                   ),
                 ],
               ),
               SizedBox(
                 height: 10,
               ),
               Row(
                 crossAxisAlignment: CrossAxisAlignment.center,
                 mainAxisAlignment: MainAxisAlignment.end,
                 children: <Widget>[
                   ElevatedButton(
                     style: ElevatedButton.styleFrom(primary: Colors.brown),
                     onPressed: () {
                       initPlatformState();
                     },
                     child: Text(
                       'Refresh',
                       style: TextStyle(color: Colors.white),
                     ),
                   ),
                   SizedBox(
                     width: 20,
                   ),
                   ElevatedButton(
                     style: ElevatedButton.styleFrom(
                         primary: _connected ? Colors.red : Colors.green),
                     onPressed: _connected ? _disconnect : _connect,
                     child: Text(
                       _connected ? 'Disconnect' : 'Connect',
                       style: TextStyle(color: Colors.white),
                     ),
                   ),
                 ],
               ),
               Padding(
                 padding:
                     const EdgeInsets.only(left: 10.0, right: 10.0, top: 50),
                 child: ElevatedButton(
                   style: ElevatedButton.styleFrom(primary: Colors.brown),
                   onPressed: () {
                     testPrint.sample(pathImage);
                   },
                   child: Text('PRINT TEST',
                       style: TextStyle(color: Colors.white)),
                 ),
               ),
             ],
           ),
         ),
       ),
     ),
   );
 }

 List<DropdownMenuItem<BluetoothDevice>> _getDeviceItems() {
   List<DropdownMenuItem<BluetoothDevice>> items = [];
   if (_devices.isEmpty) {
     items.add(DropdownMenuItem(
       child: Text('NONE'),
     ));
   } else {
     _devices.forEach((device) {
       items.add(DropdownMenuItem(
         child: Text(device.name),
         value: device,
       ));
     });
   }
   return items;
 }

 void _connect() {
   if (_device == null) {
     show('No device selected.');
   } else {
     bluetooth.isConnected.then((isConnected) {
       if (!isConnected) {
         bluetooth.connect(_device).catchError((error) {
           setState(() => _connected = false);
         });
         setState(() => _connected = true);
       }
     });
   }
 }

 void _disconnect() {
   bluetooth.disconnect();
   setState(() => _connected = false);
   
 }

//write to app path
 Future<void> writeToFile(ByteData data, String path) {
   final buffer = data.buffer;
   return new File(path).writeAsBytes(
       buffer.asUint8List(data.offsetInBytes, data.lengthInBytes));
 }

 Future show(
   String message, {
   Duration duration: const Duration(seconds: 3),
 }) async {
   await new Future.delayed(new Duration(milliseconds: 100));
   ScaffoldMessenger.of(context).showSnackBar(
     new SnackBar(
       content: new Text(
         message,
         style: new TextStyle(
           color: Colors.white,
         ),
       ),
       duration: duration,
     ),
   );
 }
}

因为此代码需要按下按钮然后才能连接蓝牙设备和断开蓝牙设备。

所以我的问题是如何编写代码让它在选择设备后自动连接蓝牙设备意味着我不需要按下任何按钮只需选择设备然后它就可以自动连接我选择的设备。

为了断开蓝牙设备,我想让它在我打印出来后自动断开,也就是在我打印出东西之后,蓝牙设备将自动断开。

我是新来的。请帮助找到解决方案。谢谢你

4

1 回答 1

1

我可能会尝试帮助您回答,所以我正在执行此代码:您必须使用“等待”来延迟打印机连接和断开连接。

void _connect(BluetoothDevice selectedDevice) {
 if (selectedDevice == null) {
   _devicesMsg = 'No device selected.';
 } else {
   printer.isConnected.then((isConnected) {
     if (!isConnected) {
        printer.connect(selectedDevice).catchError((error) {
          _devicesMsg = 'Device Error.';
        });
      }
    });
  }
}


Future<void> _startPrint() async {
//SIZE
// 0- normal size text
// 1- only bold text
// 2- bold with medium text
// 3- bold with large text
//ALIGN
// 0- ESC_ALIGN_LEFT
// 1- ESC_ALIGN_CENTER
// 2- ESC_ALIGN_RIGHT
await Future.delayed(Duration(milliseconds: 2000));
printer.isConnected.then((isConnected) {
   if (isConnected) {
     printer.printNewLine();
     printer.printCustom("HEADER", 3, 1);
     printer.paperCut();
    }
  });
}

并在成功打印数据后尝试断开连接。

Future<void> _disconnect() async {
  await Future.delayed(Duration(milliseconds: 3000));
  printer.disconnect();
}

最后你可以使用 Modal Bottom Sheet 来完成你的打印按钮:

void _settingModalBottomSheet(context) {
showModalBottomSheet(
    context: context,
    builder: (BuildContext bc) {
      return Container(
        height: 100,
        child: _devices.isEmpty
            ? Center(child: Text(_devicesMsg ?? ''))
            : ListView.builder(
                itemCount: _devices.length,
                itemBuilder: (c, i) {
                  return ListTile(
                    leading: Icon(Icons.print),
                    title: Text(
                      _devices[i].name,
                      style: whiteNumberFont.copyWith(
                          color: Colors.black,
                          fontSize: 14,
                          fontWeight: FontWeight.w800),
                    ),
                    subtitle: Text(_devices[i].address),
                    onTap: () {
                      _connect(_devices[i]);
                      _startPrint();
                      _disconnect();
                      Navigator.pop(context);
                    },
                  );
                },
              ),
          );
       });
   }

像这样的打印按钮:

ElevatedButton(
 style: ElevatedButton.styleFrom(
          elevation: 0,
          primary: mainColor,
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8)),
          ),
          child: Text(
              "PRINT",
              style: whiteTextFont.copyWith(
              fontSize: 16, color: Colors.white),
          ),
          onPressed: () {
            _settingModalBottomSheet(context);
          },
      ),
于 2022-02-18T17:18:03.123 回答