brady_flutter_plugin 3.0.0+2 copy "brady_flutter_plugin: ^3.0.0+2" to clipboard
brady_flutter_plugin: ^3.0.0+2 copied to clipboard

The official Flutter Plugin to integrate the Brady SDK into your Flutter application. The Brady SDK allows users to discover, connect, and print to Brady printers.

example/lib/main.dart

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:brady_flutter_plugin/brady_flutter_plugin.dart';
import 'package:permission_handler/permission_handler.dart';

Uint8List? previewImage;

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

class MyApp extends StatefulWidget {
  const MyApp({super.key});

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

class _MyAppState extends State<MyApp> {
  final _bradyFlutterPlugin = BradyFlutterPlugin();

  bool showImage = false;
  var isTemplate = true;

  @override
  void initState() {
    super.initState();
  }

  Future<void> discover() async {
    Map<Permission, PermissionStatus> statuses = await [
      Permission.bluetooth,
      Permission.bluetoothConnect,
      Permission.bluetoothScan,
      Permission.nearbyWifiDevices,
      Permission.locationWhenInUse
    ].request();

    _bradyFlutterPlugin.startBlePrinterDiscovery();
    _bradyFlutterPlugin.startWifiPrinterDiscovery();
  }

  Future<void> connect() async {
    /// Get a list of all discovered printers and how they were discovered (Bluetooth or Wi-Fi).
    /// Could display the list to let a user select one.
    Map<String, String> printerMap = await _bradyFlutterPlugin.getPrinters();
    bool? connected;
    for (var printer in printerMap.keys) {
      try {
        /**
         * The following lines of code show how to implement auto-connect.
         *
         * "If there was a previously connected printer, find a discovered printer
         * matching its name and connect to it."
         *
         * final printerToConnectTo = _bradyFlutterPlugin.getLastConnectedPrinterName()
         * if (printer == printerToConnectTo) {
         *    final userSelectedProtocol = printerMap[printer] == "BLE" ? true : false;
         *    final connected = await _bradyFlutterPlugin.connect(printer, userSelectedProtocol);
         * }
         */
        //TODO: REPLACE THE VALUE BELOW WITH YOUR PRINTER NAME.
        if (printer == "S3700-PGS372308901005") {
          /**
           * You may allow the user to select whether to connect via Bluetooth or Wi-Fi.
           * If they select Bluetooth (BLE), pass in "true" to the connect method.
           * If they select Wi-Fi, pass in "false" to the connect method.
           * If you don't give them the option, passing in null ignores the
           * protocol and connects to any printer with the matching name
           *
           * Refer to https://sdk.bradyid.com/supported_printers/ for supported connections.
           * For example, an M211 can only connect via Bluetooth so don't give
           * an option to connect via Wi-Fi.
           */
          final userSelectedProtocol =
              printerMap[printer] == "BLE" ? true : false;
          connected = await _bradyFlutterPlugin.connect(
              printer, true /*userSelectedProtocol*/);
          if (connected == true) {
            debugPrint("CONNECTED!");
          } else {
            debugPrint("FAILED TO CONNECT!");
          }
          break;
        }
      } on PlatformException catch (e) {
        if (kDebugMode) {
          print("Where: ${e.message!}\nDetails: ${e.details}");
        }
      }
    }
  }

  void setTemplate() async {
    //TODO: REPLACE THE VALUE BELOW WITH YOUR TEMPLATE NAME.
    try {
      final byteData =
          await rootBundle.load("assets/code128anotexttemplate.BWT");
      final bytes = byteData.buffer.asUint8List();
      await _bradyFlutterPlugin.setTemplateWithBase64(
          base64.encode(bytes), true);
      /**
       * The commented code below shows how to set an image (png, jpg, etc.) to
       * print instead of a template.
       *
       * final byteData = await rootBundle.load("assets/bitmap_rectangular_barcode.png");
       * final bytes = byteData.buffer.asUint8List();
       * _bradyFlutterPlugin.setTemplateWithBase64(base64.encode(bytes), false);
       */
    } on PlatformException catch (e) {
      if (kDebugMode) {
        print(
            "Error setting the template.\nWhere: ${e.message!}\nDetails: ${e.details}");
      }
    }

    try {
      //TODO: REPLACE THE VALUES BELOW WITH YOUR TEMPLATE'S PLACEHOLDER NAME'S.
      await _bradyFlutterPlugin.setPlaceholderValue("BARCODE 1", "HELLO WORLD");
    } on PlatformException catch (e) {
      if (kDebugMode) {
        print(
            "Error setting a placeholder.\nWhere: ${e.message!}\nDetails: ${e.details}");
      }
    }

    /// How to retrieve Placeholder information from a BWT file (template).
    try {
      final templateData = await _bradyFlutterPlugin.getTemplateData();
      for (var key in templateData.keys) {
        debugPrint("getTemplateDataNames() -> $key");
        debugPrint("getTemplateDataTypes() -> ${templateData[key]}");
      }
    } on PlatformException catch (e) {
      if (kDebugMode) {
        print(
            "Error getting template data names.\nWhere: ${e.message!}\nDetails: ${e.details}");
      }
    }

    /// Retrieve all information about the connected printer.
    try {
      var details = "";
      details +=
          "Connection Status: ${await _bradyFlutterPlugin.getPrinterStatus()}";
      details += " (${await _bradyFlutterPlugin.getConnectionType()})\n";
      details +=
          "Connection Status Message: ${await _bradyFlutterPlugin.getPrinterStatusMessage()}\n";
      details +=
          "Connection Status Message Title: ${await _bradyFlutterPlugin.getPrinterStatusMessageTitle()}\n";
      details +=
          "Connection Status Remedy Explanation Message: ${await _bradyFlutterPlugin.getPrinterStatusRemedyExplanationMessage()}\n";
      details +=
          "Has Ownership: ${await _bradyFlutterPlugin.getHaveOwnership()}\n";
      details += "Printer Name: ${await _bradyFlutterPlugin.getPrinterName()}";
      details += " (${await _bradyFlutterPlugin.getPrinterModel()})\n";
      details +=
          "Last Connected Printer: ${await _bradyFlutterPlugin.getLastConnectedPrinterName()}\n";
      details += "Supply Name: ${await _bradyFlutterPlugin.getSupplyName()}\n";
      details +=
          "Template Supply Name: ${await _bradyFlutterPlugin.getTemplateSupplyName()}\n";
      details += "Y Number: ${await _bradyFlutterPlugin.getYNumber()}\n";
      details +=
          "Supply Dimensions: ${await _bradyFlutterPlugin.getSupplyWidth()}"
          "in. x  ${await _bradyFlutterPlugin.getSupplyHeight()}in.\n";
      details +=
          "Supply Color: ${(await _bradyFlutterPlugin.getSupplyColor())!.value.toString()}\n";
      details +=
          "Remaining Supply: ${await _bradyFlutterPlugin.getSupplyRemainingPercentage()}\n";
      details += "Ribbon Name: ${await _bradyFlutterPlugin.getRibbonName()}\n";
      details +=
          "Remaining Ribbon: ${await _bradyFlutterPlugin.getRibbonRemainingPercentage()}\n";
      details +=
          "Ribbon Color: ${(await _bradyFlutterPlugin.getRibbonColor())!.value.toString()}\n";
      details +=
          "Battery Level: ${await _bradyFlutterPlugin.getBatteryLevelPercentage()}";
      details +=
          ", Charging: ${await _bradyFlutterPlugin.getIsAcConnected()}\n";
      details +=
          "PreSized: ${await _bradyFlutterPlugin.getIsSupplyPreSized()}\n";
      details += "Supplies Match: ${await _bradyFlutterPlugin.suppliesMatch()}";
      debugPrint(details);
    } on PlatformException catch (e) {
      if (kDebugMode) {
        print(
            "Error getting printer details.\n Where: ${e.message!}\nDetails: ${e.details}");
      }
    }
  }

  /// Prints out the set Template object.
  Future<void> printTemplate() async {
    try {
      final printed = await _bradyFlutterPlugin.print(1, false, true, true);
      if (printed == true) {
        debugPrint("PRINTING SUCCESSFUL!");
      } else {
        debugPrint("PRINTING FAILED!");
      }
    } on PlatformException catch (e) {
      if (kDebugMode) {
        print("Where: ${e.message!}\nDetails: ${e.details}");
      }
    }
  }

  /// Only applicable to M211 and M511. Read documentation at sdk.bradyid.com
  Future<void> feedSupply() async {
    try {
      final fed = await _bradyFlutterPlugin.feedSupply();
      if (fed == true) {
        debugPrint("FED SUCCESSFUL!");
      } else {
        debugPrint("FED FAILED!");
      }
    } on PlatformException catch (e) {
      if (kDebugMode) {
        print("Where: ${e.message!}\nDetails: ${e.details}");
      }
    }
  }

  /// Only applicable to M211 and M511. Read documentation at sdk.bradyid.com
  Future<void> cutSupply() async {
    try {
      final cut = await _bradyFlutterPlugin.cutSupply();
      if (cut == true) {
        debugPrint("CUT SUCCESSFUL!");
      } else {
        debugPrint("CUT FAILED!");
      }
    } on PlatformException catch (e) {
      if (kDebugMode) {
        print("Where: ${e.message!}\nDetails: ${e.details}");
      }
    }
  }

  /// Only applicable to the M211 and M511. Read documentation at sdk.bradyid.com
  Future<void> setAutomaticShutoffTime() async {
    try {
      final setResult = await _bradyFlutterPlugin.setAutomaticShutoffTime(30);
      if (setResult == true) {
        debugPrint("AUTOMATIC SHUTOFF TIME SET SUCCESSFULLY!");
      } else {
        debugPrint("AUTOMATIC SHUTOFF TIME SET FAILED!");
      }
    } on PlatformException catch (e) {
      if (kDebugMode) {
        print("Where: ${e.message!}\nDetails: ${e.details}");
      }
    }
  }

  /// This method is the combination of the two methods below it.
  /// disconnect = disconnectWithoutForget + forgetLastConnectedPrinter
  Future<void> disconnect() async {
    try {
      final disconnected = await _bradyFlutterPlugin.disconnect();
      if (disconnected == true) {
        debugPrint("DISCONNECT SUCCESSFUL!");
      } else {
        debugPrint("DISCONNECT FAILED!");
      }
    } on PlatformException catch (e) {
      if (kDebugMode) {
        print("Where: ${e.message!}\nDetails: ${e.details}");
      }
    }
  }

  /// Disconnects from a printer while saving getLastConnectedPrinterName
  Future<void> disconnectWithoutForget() async {
    try {
      final disconnected = await _bradyFlutterPlugin.disconnectWithoutForget();
      if (disconnected == true) {
        debugPrint("DISCONNECT SUCCESSFUL!");
      } else {
        debugPrint("DISCONNECT FAILED!");
      }
    } on PlatformException catch (e) {
      if (kDebugMode) {
        print("Where: ${e.message!}\nDetails: ${e.details}");
      }
    }
  }

  /// This sets the result of getLastConnectedPrinterName to null.
  Future<void> forgetLastConnectedPrinter() async {
    try {
      await _bradyFlutterPlugin.forgetLastConnectedPrinter();
    } on PlatformException catch (e) {
      if (kDebugMode) {
        print("Where: ${e.message!}\nDetails: ${e.details}");
      }
    }
  }

  /// Shows an image of what will print out.
  Future<void> getPreview() async {
    try {
      var base64 = await _bradyFlutterPlugin.getPreview(200);
      previewImage = base64Decode(base64!);
      setState(() {
        showImage = true;
      });
    } on PlatformException catch (e) {
      if (kDebugMode) {
        print("Where: ${e.message!}\nDetails: ${e.details}");
      }
    }
  }

  Future<void> getAvailableUpdates() async {
    /**
     * Each time a change occurs on the connected printer, it will add the property
     * to an internal list as a string. Calling getAvailablePrinterUpdates()
     * retrieves the list of strings and clears the list. Refer to
     * https://sdk.bradyid.com/printer_properties_ios/ to see all property keys.
     */
    var updatesList = await _bradyFlutterPlugin.getAvailablePrinterUpdates();
    for (int i = 0; i < updatesList.length; i++) {
      /**
       * For example, you could loop through the updates. When a string
       * equals "BatteryChargePercentage", you could update a battery symbol
       * in your UI using the value from printerDetails.getBatteryLevelPercentage()..
       */
      debugPrint(updatesList[i]);
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      appBar: AppBar(
        title: const Text('Plugin example app'),
      ),
      body: SingleChildScrollView(
        child: Stack(
          children: <Widget>[
            Column(
              children: [
                ElevatedButton(
                    onPressed: () {
                      discover();
                    },
                    child: const Text('Start Discovery')),
                ElevatedButton(
                    onPressed: () {
                      connect();
                    },
                    child: const Text('Connect')),
                ElevatedButton(
                    onPressed: () {
                      setTemplate();
                    },
                    child: const Text('Set Template')),
                ElevatedButton(
                    onPressed: () {
                      printTemplate();
                    },
                    child: const Text('Print')),
                ElevatedButton(
                    onPressed: () {
                      feedSupply();
                    },
                    child: const Text('Feed')),
                ElevatedButton(
                    onPressed: () {
                      cutSupply();
                    },
                    child: const Text('Cut')),
                ElevatedButton(
                    onPressed: () {
                      setAutomaticShutoffTime();
                    },
                    child: const Text('Set Auto Shutoff')),
                ElevatedButton(
                    onPressed: () {
                      disconnect();
                    },
                    child: const Text('Disconnect')),
                ElevatedButton(
                    onPressed: () {
                      disconnectWithoutForget();
                    },
                    child: const Text('Disconnect Without Forget')),
                ElevatedButton(
                    onPressed: () {
                      forgetLastConnectedPrinter();
                    },
                    child: const Text('Forget')),
                ElevatedButton(
                    onPressed: () {
                      getPreview();
                    },
                    child: const Text('Show Print Preview')),
                ElevatedButton(
                    onPressed: () {
                      getAvailableUpdates();
                    },
                    child: const Text('Get Available Updates')),
                showImage
                    ? Column(
                        children: [
                          Image.memory(previewImage!),
                        ],
                      )
                    : const SizedBox(
                        height: 0,
                      ),
              ],
            ),
          ],
        ),
      ),
    ));
  }
}
2
likes
150
pub points
4%
popularity

Publisher

verified publishersdk.bradyid.com

The official Flutter Plugin to integrate the Brady SDK into your Flutter application. The Brady SDK allows users to discover, connect, and print to Brady printers.

Homepage

Documentation

API reference

License

unknown (license)

Dependencies

flutter, plugin_platform_interface

More

Packages that depend on brady_flutter_plugin