Advertisement
kendy2900

seting printer

Apr 25th, 2022
954
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 12.16 KB | None | 0 0
  1. import 'package:blue_thermal_printer/blue_thermal_printer.dart';
  2. import 'package:te111/models/printer.dart';
  3. import 'package:te111/utils/database_helper.dart';
  4. import 'package:flutter/material.dart';
  5. import 'package:flutter/services.dart';
  6. import 'package:shared_preferences/shared_preferences.dart';
  7.  
  8. class Print extends StatefulWidget {
  9.   static const routeName = '/print';
  10.  
  11.   @override
  12.   _PrintState createState() => _PrintState();
  13. }
  14.  
  15. class _PrintState extends State<Print> {
  16.   BlueThermalPrinter bluetooth = BlueThermalPrinter.instance;
  17.  
  18.   final formkey = GlobalKey<FormState>();
  19.   final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  20.  
  21.   List<BluetoothDevice> _devices = [];
  22.   BluetoothDevice? _device;
  23.   bool _connected = false, _onBluetooth = false;
  24.  
  25.   late SharedPreferences preferences;
  26.  
  27.   // Printer _printer;
  28.   late AppPrint _appPrint;
  29.  
  30.   String nameDevice = '', addressDevice = '', prefPrint = '';
  31.  
  32.   int? pId = 1, pType = 0, pConnected = 0;
  33.   String? pName = '', pAddress = '';
  34.  
  35.   bool conn = false;
  36.   bool isSwitched = false;
  37.  
  38.   savePrint(String printAddress, String printName) async {
  39.     SharedPreferences preferences = await SharedPreferences.getInstance();
  40.     setState(() {
  41.       preferences.setString('print', printAddress);
  42.       preferences.setString('printer_name', printName);
  43.       preferences.commit();
  44.     });
  45.   }
  46.  
  47.   pref() async {
  48.     preferences = await SharedPreferences.getInstance();
  49.     setState(() {
  50.       prefPrint = (preferences.getString('print') ?? 'AddresPrint');
  51.     });
  52.   }
  53.  
  54.   Future<void> getPrint() async {
  55.     var db = DatabaseHelper();
  56.     List<Printer> res = await db.getDataPrint();
  57.     res.forEach((element) {
  58.       pName = element.name;
  59.       pAddress = element.address;
  60.       pConnected = element.connected;
  61.     });
  62.   }
  63.  
  64.   Future updatePrint() async {
  65.     var db = DatabaseHelper();
  66.     var uPrint = new Printer(pName, pAddress, pConnected);
  67.     await db.updatePrint(uPrint, pId);
  68.   }
  69.  
  70.   check() {
  71.     // print("Cek Addr $pAddress");
  72.     final form = formkey.currentState!;
  73.     if (form.validate()) {
  74.       form.save();
  75.       // print("Addres Print $pAddress");
  76.       updatePrint();
  77.     }
  78.   }
  79.  
  80.   void back() {
  81.     Navigator.of(context).pop();
  82.     // Navigator.of(context)
  83.     //     .push(MaterialPageRoute(builder: (context) => Dashboard()));
  84.   }
  85.  
  86.   // Future<bool> _onWillPop() {
  87.   //   back();
  88.   // }
  89.  
  90.   @override
  91.   void setState(fn) {
  92.     if (mounted) {
  93.       super.setState(fn);
  94.     }
  95.   }
  96.  
  97.   @override
  98.   void initState() {
  99.     getPrint();
  100.     if (pConnected == 0) {
  101.       setState(() => isSwitched = false);
  102.     } else {
  103.       setState(() => isSwitched = true);
  104.     }
  105.     initPlatformState();
  106.     _appPrint = AppPrint();
  107.     super.initState();
  108.   }
  109.  
  110.   Future<void> initPlatformState() async {
  111.     bool? isConnected = await bluetooth.isConnected;
  112.     List<BluetoothDevice> devices = [];
  113.     try {
  114.       devices = await bluetooth.getBondedDevices();
  115.     } on PlatformException {}
  116.  
  117.     bluetooth.onStateChanged().listen((state) {
  118.       switch (state) {
  119.         case BlueThermalPrinter.CONNECTED:
  120.           setState(() {
  121.             _connected = true;
  122.           });
  123.           break;
  124.         case BlueThermalPrinter.DISCONNECTED:
  125.           setState(() {
  126.             _connected = false;
  127.           });
  128.           break;
  129.         default:
  130.           break;
  131.       }
  132.     });
  133.  
  134.     if (!mounted) return;
  135.     setState(() {
  136.       _devices = devices;
  137.     });
  138.  
  139.     if (isConnected!) {
  140.       setState(() {
  141.         _connected = true;
  142.       });
  143.     }
  144.   }
  145.  
  146.   @override
  147.   Widget build(BuildContext context) {
  148.     return Scaffold(
  149.       key: _scaffoldKey,
  150.       appBar: AppBar(
  151.           title: Text(
  152.             'Setting Printer',
  153.             style: TextStyle(
  154.                 fontWeight: FontWeight.w600,
  155.                 color: Colors.white,
  156.                 fontSize: 16.0),
  157.           ),
  158.           backgroundColor: Colors.lightBlue,
  159.           leading: IconButton(
  160.             icon: Icon(Icons.arrow_back),
  161.             color: Colors.white,
  162.             onPressed: () {
  163.               back();
  164.             },
  165.           )),
  166.       body: Container(
  167.         width: MediaQuery.of(context).size.width,
  168.         padding: const EdgeInsets.only(left: 20.0, right: 20.0),
  169.         child: Form(
  170.           key: formkey,
  171.           child: ListView(
  172.             children: <Widget>[
  173.               Column(
  174.                 children: <Widget>[
  175.                   SizedBox(
  176.                     height: 10.0,
  177.                   ),
  178.                   Row(
  179.                     crossAxisAlignment: CrossAxisAlignment.center,
  180.                     mainAxisAlignment: MainAxisAlignment.spaceBetween,
  181.                     children: <Widget>[
  182.                       RaisedButton(
  183.                         color: Colors.green,
  184.                         onPressed: () {
  185.                           bluetooth.openSettings;
  186.                         },
  187.                         child: Text(
  188.                           'Nyalakan Bluetooth',
  189.                           style: TextStyle(color: Colors.white),
  190.                         ),
  191.                       ),
  192.                       Text('Auto Connect'),
  193.                       Switch(
  194.                         value: isSwitched,
  195.                         onChanged: (value) {
  196.                           setState(() {
  197.                             isSwitched = value;
  198.                             if (value == false) {
  199.                               pConnected = 0;
  200.                             } else {
  201.                               pConnected = 1;
  202.                             }
  203.                           });
  204.                         },
  205.                         activeTrackColor: Colors.lightGreenAccent,
  206.                         activeColor: Colors.green,
  207.                       ),
  208.                     ],
  209.                   ),
  210.                   Container(
  211.                     padding:
  212.                         const EdgeInsets.only(left: 10.0, right: 10.0, top: 20),
  213.                     child: Text('Pilih Bluetooth Device Printer'),
  214.                   ),
  215.                   Row(
  216.                       crossAxisAlignment: CrossAxisAlignment.center,
  217.                       mainAxisSize: MainAxisSize.max,
  218.                       children: <Widget>[
  219.                         SafeArea(
  220.                           top: false,
  221.                           left: false,
  222.                           right: false,
  223.                           bottom: false,
  224.                           child: Container(
  225.                             child: DropdownButton(
  226.                               items: _getDeviceItems(),
  227.                               onChanged: (dynamic value) {
  228.                                 setState(() {
  229.                                   _device = value;
  230.                                 });
  231.                               },
  232.                               value: _device,
  233.                             ),
  234.                           ),
  235.                         ),
  236.                       ]),
  237.                   SizedBox(
  238.                     height: 10,
  239.                   ),
  240.                   Container(
  241.                     child: Row(
  242.                       mainAxisAlignment: MainAxisAlignment.spaceBetween,
  243.                       children: <Widget>[],
  244.                     ),
  245.                   ),
  246.                   Row(
  247.                     crossAxisAlignment: CrossAxisAlignment.center,
  248.                     mainAxisAlignment: MainAxisAlignment.spaceBetween,
  249.                     children: <Widget>[
  250.                       RaisedButton(
  251.                         color: Colors.brown,
  252.                         onPressed: () {
  253.                           _scaffoldKey.currentState!.showSnackBar(new SnackBar(
  254.                             duration: new Duration(seconds: 2),
  255.                             content: new Row(
  256.                               children: <Widget>[
  257.                                 new CircularProgressIndicator(),
  258.                                 new Text("  Refresh...")
  259.                               ],
  260.                             ),
  261.                           ));
  262.                           initPlatformState();
  263.                         },
  264.                         child: Text(
  265.                           'Refresh',
  266.                           style: TextStyle(color: Colors.white),
  267.                         ),
  268.                       ),
  269.                       // SizedBox(
  270.                       //   width: 20,
  271.                       // ),
  272.                       RaisedButton(
  273.                         color: _connected ? Colors.red : Colors.green,
  274.                         onPressed: _connected ? _disconnect : _connect,
  275.                         child: Text(
  276.                           _connected ? 'Disconnect' : 'Connect',
  277.                           style: TextStyle(color: Colors.white),
  278.                         ),
  279.                       ),
  280.                       // SizedBox(
  281.                       //   width: 20,
  282.                       // ),
  283.                       RaisedButton(
  284.                         color: Colors.blue,
  285.                         onPressed: () {
  286.                           savePrint(addressDevice, nameDevice);
  287.                           updatePrint();
  288.                           print(addressDevice + ' ' + nameDevice);
  289.                         },
  290.                         child: Text(
  291.                           'Simpan Printer',
  292.                           style: TextStyle(color: Colors.white),
  293.                         ),
  294.                       ),
  295.                     ],
  296.                   ),
  297.                   Container(
  298.                     padding:
  299.                         const EdgeInsets.only(left: 10.0, right: 10.0, top: 20),
  300.                     child: Center(
  301.                       child: Text(
  302.                           'Jika auto connect di gunakan, Bluetooth Device dan Printer harus menyala !'),
  303.                     ),
  304.                   ),
  305.                   Container(
  306.                     padding:
  307.                         const EdgeInsets.only(left: 10.0, right: 10.0, top: 20),
  308.                     child: Center(
  309.                       child:
  310.                           Text(_connected ? 'Connected to ' + nameDevice : ''),
  311.                     ),
  312.                   ),
  313.                   Container(
  314.                     padding: const EdgeInsets.only(left: 10.0, right: 10.0),
  315.                     child: Center(
  316.                       child: Text(
  317.                           _connected ? 'Connected to ' + addressDevice : ''),
  318.                     ),
  319.                   ),
  320.                   Container(
  321.                     width: double.infinity,
  322.                     padding:
  323.                         const EdgeInsets.only(left: 10.0, right: 10.0, top: 20),
  324.                     child: RaisedButton(
  325.                       color: Colors.green,
  326.                       onPressed: () {
  327.                         _appPrint.testPrint();
  328.                       },
  329.                       child: Text('Test Print',
  330.                           style: TextStyle(color: Colors.white)),
  331.                     ),
  332.                   ),
  333.                 ],
  334.               ),
  335.             ],
  336.           ),
  337.         ),
  338.       ),
  339.     );
  340.   }
  341.  
  342.   List<DropdownMenuItem<BluetoothDevice>> _getDeviceItems() {
  343.     List<DropdownMenuItem<BluetoothDevice>> items = [];
  344.     if (_devices.isEmpty) {
  345.       items.add(DropdownMenuItem(
  346.         child: Text('NONE'),
  347.       ));
  348.     } else {
  349.       _devices.forEach((device) {
  350.         setState(() {
  351.           nameDevice = device.name!;
  352.           addressDevice = device.address!;
  353.           pName = device.name;
  354.           pAddress = device.address;
  355.           check();
  356.         });
  357.         items.add(DropdownMenuItem(
  358.           child: Text(device.name!),
  359.           value: device,
  360.         ));
  361.       });
  362.     }
  363.     return items;
  364.   }
  365.  
  366.   void _connect() {
  367.     if (_device == null) {
  368.     } else {
  369.       bluetooth.isConnected.then((isConnected) {
  370.         if (!isConnected!) {
  371.           bluetooth.connect(_device!).catchError((error) {
  372.             setState(() => _connected = false);
  373.           });
  374.           setState(() => _connected = true);
  375.         }
  376.       });
  377.     }
  378.   }
  379.  
  380.   void _disconnect() {
  381.     bluetooth.disconnect();
  382.     setState(() => _connected = true);
  383.   }
  384. }
  385.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement