Advertisement
kendy2900

setting printer revisi

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