<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alex Bordei 💙 💙 💙 on Medium]]></title>
        <description><![CDATA[Stories by Alex Bordei 💙 💙 💙 on Medium]]></description>
        <link>https://medium.com/@alex.bordei1991?source=rss-66ccae38d2d2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wW4vJ2s8eBSttPt-7U0WSg.jpeg</url>
            <title>Stories by Alex Bordei 💙 💙 💙 on Medium</title>
            <link>https://medium.com/@alex.bordei1991?source=rss-66ccae38d2d2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 00:59:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alex.bordei1991/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Why Flutter Excels at Thermal Printer Integration for Kiosks and POS]]></title>
            <link>https://medium.com/@alex.bordei1991/why-flutter-excels-at-thermal-printer-integration-for-kiosks-and-pos-5bf21224c613?source=rss-66ccae38d2d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bf21224c613</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[pos]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Alex Bordei   ]]></dc:creator>
            <pubDate>Thu, 01 May 2025 06:23:28 GMT</pubDate>
            <atom:updated>2025-05-01T06:41:19.898Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fi4npGiYzsPs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2Fi4npGiYzsPs%3Ffeature%3Dshare&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fi4npGiYzsPs%2Fhq2.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/98f3a03e64051499de5d8fe8a719450b/href">https://medium.com/media/98f3a03e64051499de5d8fe8a719450b/href</a></iframe><p>Integrating thermal printers in kiosk or POS applications can be challenging, but <strong>Flutter</strong> makes it surprisingly seamless. As kiosk manufacturers and POS software providers look for efficient, cross-platform solutions, Flutter stands out as an ideal choice for driving ESC/POS thermal printers. From receipt printing in payment kiosks to generating transaction slips on mobile POS devices, Flutter’s rich ecosystem of packages (like <strong>esc_pos_utils_plus</strong>) and its hardware abstraction capabilities shine. In this article, we’ll explore why Flutter is a perfect fit for thermal printer integration, backed by real-world examples and code-heavy sections that demonstrate how to get it done.</p><h3>Flutter’s Cross-Platform Edge in Kiosks &amp; POS</h3><p>Flutter is Google’s open-source UI framework that compiles to native code on <strong>Android, iOS, Windows, macOS, Linux</strong>, and even the web. This cross-platform reach is particularly useful for kiosks and POS systems, which often need to run on various hardware setups:</p><ul><li><strong>Single Codebase:</strong> You write your printer logic once in <strong>Dart</strong>, and <strong>Flutter</strong> ensures it runs consistently on different <strong>OSes</strong> (even on embedded <strong>Android devices</strong> or custom <strong>Linux kiosks</strong>).</li><li><strong>Native Performance:</strong> Flutter’s <strong>AOT-compiled</strong> code runs at native speed. Thermal printer interactions (often involving streaming bytes) benefit from this performance.</li><li><strong>UI + Hardware in One Place:</strong> Flutter can handle the entire kiosk/POS UI <strong>and</strong> the hardware calls to the printer, eliminating the complexity of bridging multiple languages or systems.</li><li><strong>Plugin Ecosystem:</strong> Flutter’s plugin system allows tapping into native APIs for Bluetooth, USB, or network communication. Many community packages exist to simplify connecting to thermal printers over various interfaces.</li></ul><p>In kiosk scenarios, Flutter can manage everything from <strong>touchscreen UI</strong> to <strong>printing receipts</strong> — all with unified business logic. This reduces development and maintenance costs, a key consideration for <strong>kiosk manufacturers</strong> and <strong>POS software providers</strong>.</p><h3>ESC/POS in a Nutshell</h3><p>Before diving into Flutter specifics, let’s quickly recap ESC/POS. <strong>ESC/POS (Epson Standard Code for Printers)</strong> is a widely used command protocol for thermal and receipt printers. It defines a set of binary commands that control printer features (text, images, barcodes, cut paper, etc.). Thermal printers used in retail, banking, and kiosks almost universally understand ESC/POS commands.</p><h3>Why ESC/POS Matters for Flutter</h3><p>Flutter doesn’t natively “know” about ESC/POS, but its flexible Dart environment can generate and send these commands. By integrating an ESC/POS library, your Flutter app can:</p><ul><li><strong>Print text with styles:</strong> Choose fonts, bold/underline, alignment, etc., via ESC/POS commands.</li><li><strong>Print images, barcodes, and QR codes:</strong> Encode graphics or codes to bytes the printer understands.</li><li><strong>Control printer hardware:</strong> Send commands to cut paper, beep, or open cash drawers (if supported by the printer).</li></ul><p>In short, with ESC/POS support, Flutter can fully emulate the capabilities of a typical point-of-sale terminal’s printing subsystem.</p><h3>Key Flutter Packages for Thermal Printing</h3><p>The Flutter community has developed several packages to simplify ESC/POS printing. Some of the <strong>popular choices</strong> include:</p><ul><li><strong>esc_pos_utils_plus:</strong> A Dart package that generates ESC/POS command bytes from human-readable instructions. It’s an improved, Dart 3 compatible fork of the original <strong>esc_pos_utils</strong>.</li><li><strong>esc_pos_printer &amp; </strong><strong>esc_pos_bluetooth:</strong> Packages for network (WiFi/Ethernet) and Bluetooth printing respectively. They use <strong>esc_pos_utils</strong> under the hood to format data and handle the connectivity to printers <a href="https://pub.dev/packages/esc_pos_utils_plus">pub.dev</a>.</li><li><strong>print_bluetooth_thermal:</strong> A plugin for direct Bluetooth printing on Android/iOS, often used alongside <strong>esc_pos_utils_plus</strong> for crafting the print content.</li><li><strong>flutter_thermal_printer:</strong> A newer plugin that abstracts printing over <strong>Bluetooth, USB, BLE, and WiFi</strong> in one unified API.</li><li><strong>flutter_blue or </strong><strong>blue_thermal_print:</strong> General Bluetooth (BLE) connectivity packages that can pair with printers (though printing raw bytes often still relies on <strong>esc_pos_utils</strong> to craft those bytes).</li></ul><p>Each of these serves a role: one group handles <strong>formatting (ESC/POS utils)</strong>, the others handle <strong>transport (Bluetooth, USB, network)</strong>. Let’s take a closer look at how to use <strong>esc_pos_utils_plus</strong> with a transport plugin to print a simple receipt.</p><h3>Generating ESC/POS Commands with esc_pos_utils_plus</h3><p>The <strong>esc_pos_utils_plus</strong> package focuses on <strong>formatting</strong> – turning text, images, and other content into ESC/POS command bytes. You typically use its <strong>Generator</strong> class to build a list of bytes, which you later send to the printer. Below is an example of creating a simple receipt ticket:</p><pre>import &#39;package:esc_pos_utils_plus/esc_pos_utils.dart&#39;;<br>import &#39;package:esc_pos_utils_plus/esc_pos_utils_plus.dart&#39;; // For new features, if any<br><br>Future&lt;List&lt;int&gt;&gt; generateReceiptBytes() async {<br>  // Load default capability profile (includes font and code page info)<br>  final profile = await CapabilityProfile.load();<br>  final generator = Generator(PaperSize.mm80, profile);  // 80mm paper width<br>  List&lt;int&gt; bytes = [];<br><br>  // Header text centered, bold<br>  bytes += generator.text(<br>    &#39;My Store, Inc.&#39;,<br>    styles: PosStyles(align: PosAlign.center, bold: true, height: PosTextSize.size2, width: PosTextSize.size2),<br>    linesAfter: 1,<br>  );<br><br>  // Body: Itemized purchase list (using columns)<br>  bytes += generator.row([<br>    PosColumn(text: &#39;Item&#39;, width: 6, styles: PosStyles(bold: true)),<br>    PosColumn(text: &#39;Qty&#39;, width: 2, styles: PosStyles(bold: true)),<br>    PosColumn(text: &#39;Price&#39;, width: 4, styles: PosStyles(bold: true)),<br>  ]);<br>  bytes += generator.row([<br>    PosColumn(text: &#39;Coffee&#39;, width: 6),<br>    PosColumn(text: &#39;2&#39;, width: 2),<br>    PosColumn(text: &#39;\\$5.00&#39;, width: 4),<br>  ]);<br>  bytes += generator.row([<br>    PosColumn(text: &#39;Bagel&#39;, width: 6),<br>    PosColumn(text: &#39;1&#39;, width: 2),<br>    PosColumn(text: &#39;\\$2.50&#39;, width: 4),<br>  ]);<br>  bytes += generator.hr(); // horizontal rule<br><br>  // Total<br>  bytes += generator.text(&#39;Total: \\$7.50&#39;,<br>      styles: PosStyles(align: PosAlign.right, bold: true));<br><br>  // QR Code at the end (e.g., link to survey)<br>  bytes += generator.qrcode(&#39;&lt;https://example.com/survey&gt;&#39;, size: QRSize.Size4);<br>  <br>  // Cut the paper (if supported)<br>  bytes += generator.feed(2);<br>  bytes += generator.cut();<br>  return bytes;<br>}</pre><p>In the code above, we use various features of <strong>esc_pos_utils_plus</strong>:</p><ul><li><strong>Text styling:</strong> Setting alignment, bold, and text size (200% in this case).</li><li><strong>Columns:</strong> We formatted a 3-column layout for items, using the <strong>row</strong> method with <strong>PosColumn</strong> definitions (specifying relative column widths).</li><li><strong>Horizontal rules:</strong> <strong>generator.hr()</strong> to add a separator line.</li><li><strong>Barcodes/QR codes:</strong> Using <strong>generator.qrcode()</strong> to embed a QR code (similarly, <strong>generator.barcode()</strong> exists for various barcode types).</li><li><strong>Paper cut:</strong> <strong>generator.cut()</strong> to issue a cut command at the end of the ticket.</li></ul><p>The result of this function is a <strong>List&lt;int&gt;</strong> of bytes. The next step is <strong>sending these bytes to the printer</strong> via whichever connection method we use (Bluetooth, USB, or network).</p><h3>Flutter Printing via Bluetooth</h3><p>Bluetooth is a common interface for portable thermal printers (think of handheld POS devices or small receipt printers in cafes). Flutter can handle Bluetooth printing in multiple ways:</p><ul><li>Using a specific plugin like <strong>print_bluetooth_thermal</strong> (which provides a straightforward API for pairing and printing).</li><li>Using general Bluetooth access (<strong>flutter_blue</strong>) combined with writing to the device’s characteristic (a bit more work).</li><li>The new <strong>flutter_thermal_printer</strong> plugin, which supports Bluetooth and even BLE out of the box with a unified API <a href="https://pub.dev/packages/flutter_thermal_printer">pub.dev.</a></li></ul><p>Let’s focus on the popular approach with <strong>print_bluetooth_thermal</strong> as an example, since it’s often mentioned for ESC/POS and is Android/iOS friendly.</p><p><strong>1. Permissions:</strong> On Android, you need Bluetooth permissions in the manifest, and on iOS you need usage descriptions. For example:</p><pre>&lt;!-- AndroidManifest.xml --&gt;<br>&lt;uses-permission android:name=&quot;android.permission.BLUETOOTH_CONNECT&quot; /&gt;</pre><pre>&lt;!-- iOS Info.plist --&gt;<br>&lt;key&gt;NSBluetoothAlwaysUsageDescription&lt;/key&gt;<br>&lt;string&gt;Bluetooth access to connect thermal printers&lt;/string&gt;</pre><p>These ensure the OS allows the app to use Bluetooth.</p><p><strong>2. Scanning for Devices:</strong> <strong>PrintBluetoothThermal</strong> usually has methods to list paired devices. For instance:</p><pre>List&lt;BluetoothInfo&gt; pairedDevices = await PrintBluetoothThermal.pairedBluetooths;</pre><p>This returns devices the OS already knows about (paired) <a href="https://medium.com/@10urbulut/thermal-print-with-flutter-48f8aa5496a4#:~:text=We%20have%20a%20PrintBluetoothThermal%20class,a%20static%20method%20named%20%E2%80%9CpairedBluetooths%E2%80%9D">medium.com</a>. In some cases, you might use a scanning function to find new devices, but often printers are paired beforehand.</p><p><strong>3. Connecting:</strong> Once you have a device’s MAC address, you connect:</p><pre>bool connectOk = await PrintBluetoothThermal.connect(macPrinterAddress: selectedDevice.macAddress);</pre><p>This static <strong>connect</strong> method tries to establish a connection. It returns <strong>true</strong> if successful. Under the hood, it’s opening a Bluetooth socket to the printer’s Serial Port Profile (SPP).</p><p><strong>4. Sending Data:</strong> If connected, you can send the bytes we generated earlier:</p><pre>List&lt;int&gt; bytes = await generateReceiptBytes();<br>bool result = await PrintBluetoothThermal.writeBytes(bytes);</pre><p>The <strong>writeBytes</strong> method streams the ESC/POS byte list to the printer. If the printer is in range and ready, it will immediately start printing the receipt.</p><p><strong>5. Disconnecting:</strong> After printing, it’s good practice to disconnect (though some apps keep the connection open for subsequent prints):</p><pre>await PrintBluetoothThermal.disconnect();</pre><p>Using <strong>print_bluetooth_thermal</strong>, the above steps can be done in just a few lines of code, making Flutter Bluetooth printing quite straightforward. The user experience would involve the app listing available printers, the user tapping one, and then the app confirming a connection and printing.</p><h3>USB Printing from Flutter</h3><p>Many kiosks use USB thermal printers for reliability (no wireless issues) and speed. Flutter can talk to USB devices, but it’s more platform-dependent:</p><ul><li>On <strong>Android</strong>, you need USB host support and likely a plugin that interfaces with the Android USB APIs.</li><li>On <strong>Windows/Mac/Linux</strong>, if you build a desktop Flutter app, you might rely on something like a virtual COM port or specific drivers.</li></ul><p>A promising community plugin is <strong>flutter_thermal_printer</strong> which, as mentioned, supports USB printing for Android, Windows, etc., out of the box. Another approach is using a lower-level plugin or method channel:</p><p><strong>Example using a hypothetical USB method:</strong></p><p>Suppose we have a class <strong>PrintUsb</strong> (like one from a package <strong>print_usb</strong> on Windows). We would:</p><pre>List&lt;UsbDevice&gt; devices = await PrintUsb.getList();<br>if (devices.isNotEmpty) {<br>  bool connected = await PrintUsb.connect(name: devices[0].name);<br>  if (connected) {<br>    List&lt;int&gt; bytes = await generateReceiptBytes();<br>    bool success = await PrintUsb.printBytes(bytes: bytes, device: devices[0]);<br>    // Check success...<br>    await PrintUsb.close();<br>  }<br>}</pre><p>The code above does a few things akin to the <strong>print_usb</strong> package example (for Windows):</p><ul><li><strong>GetList:</strong> Enumerate USB devices and filter for known printer types.</li><li><strong>Connect:</strong> Open the USB connection to the printer (often by name or VID:PID).</li><li><strong>PrintBytes:</strong> Send the ESC/POS bytes over USB to the printer.</li><li><strong>Close:</strong> Close the connection if desired.</li></ul><p>On Android, a similar approach could be taken with a plugin that listens for USB device attach events and then communicates via USB. The specifics can differ (some printers use USB CDC, others might emulate serial). The key point is Flutter’s ability to use <strong>platform channels</strong> or existing plugins to handle USB communication.</p><p><strong>Tip:</strong> If using USB on Android, you’ll need to add <strong>uses-feature android:usb.host</strong> and request USB permission via an intent. Some plugins handle this internally.</p><h3>Network Printing (Ethernet/WiFi)</h3><p>Network-enabled printers (Ethernet or WiFi) are common in fixed terminals. They typically listen on a socket (often port 9100) for raw ESC/POS data. Flutter can leverage standard networking (using Dart’s sockets) or plugins:</p><p>A popular package for network printing is <strong>esc_pos_printer</strong>. It includes a <strong>PrinterNetworkManager</strong> to discover and print to network printers. Using it might look like:</p><pre>final manager = PrinterNetworkManager();<br>// Configure network printer<br>manager.selectPrinter(&#39;192.168.1.100&#39;, port: 9100);<br><br>List&lt;int&gt; bytes = await generateReceiptBytes();<br>final result = await manager.printTicket(bytes);</pre><p>What’s happening here:</p><ul><li><strong>Selecting Printer:</strong> Point the manager to the printer’s IP and port.</li><li><strong>Printing:</strong> The manager opens a socket and sends the bytes. <strong>printTicket</strong> returns status (success/failure).</li></ul><p>Alternatively, since Dart has native socket support, you could implement a lightweight solution:</p><pre>import &#39;dart:io&#39;;<br><br>Socket socket = await Socket.connect(&#39;192.168.1.100&#39;, 9100);<br>socket.add(await generateReceiptBytes());<br><br>socket.destroy();</pre><p>This directly sends the bytes and then closes the connection. It’s simple and doesn’t require an extra package if you’re comfortable with raw sockets.</p><p><strong>Network Discovery:</strong> The <strong>ping_discover_network</strong> package or similar can scan IP ranges to find printers, which is handy in dynamic environments. Many thermal printers use dynamic IP via DHCP, so some discovery mechanism or user input is needed.</p><h3>Real-World Deployment: Flutter + Thermal Printing in Action</h3><p>Nothing speaks louder than real-world success. Let’s consider a case study: <strong>bill payment kiosks</strong>. These kiosks allow users to pay utility bills, top-up accounts, or perform banking transactions via a self-service machine. A company like <strong>IPS (International Payments System)</strong> might deploy kiosks in various locations.</p><p>Imagine IPS building their kiosk software with Flutter:</p><ul><li><strong>Modern UI:</strong> Flutter provides a fluid touch interface for menu navigation, on-screen keyboard (perhaps using a custom <strong>flutter_virtual_keyboard</strong> published by ICEFelix), and interactive forms.</li><li><strong>Device Integration:</strong> Alongside card readers and cash acceptors, a thermal printer is integrated for receipts.</li><li><strong>Unified Development:</strong> The same Flutter app could run on an Android-based kiosk tablet or a Windows all-in-one PC, thanks to Flutter’s cross-platform nature. The printing logic remains the same.</li><li><strong>ESC/POS Printing:</strong> Using <strong>esc_pos_utils_plus</strong>, the app generates receipts (with company logo, transaction details, and a QR code for the transaction ID). Flutter can easily render the logo from assets into bytes for printing.</li><li><strong>Deployment &amp; Maintenance:</strong> Flutter’s hot-reload and quick iteration allow IPS to update the kiosk software UI and printing format swiftly without juggling multiple codebases for different machines.</li></ul><p><strong>Outcome:</strong> IPS successfully rolled out kiosks across Romania, with Flutter powering not just the user interface but also reliable receipt printing for every transaction. This demonstrates Flutter’s capability in an <strong>embedded fintech scenario</strong> — robust enough for financial transactions and printing.</p><h3>Architecture: How Flutter Talks to Thermal Printers</h3><p>To visualize the flow, here’s a simplified architecture diagram of a Flutter app printing to a thermal printer:</p><p><em>Figure: Flutter Thermal Printing Architecture.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*ZjnEOmmuXzyvXDG_XG01Lw.png" /></figure><p>At a high level, the Flutter app uses a <strong>platform plugin</strong> to communicate with the printer hardware. The <strong>esc_pos_utils_plus</strong> lives entirely in Dart (within Flutter), converting text or images to ESC/POS bytes. Those bytes travel via a platform channel to the native side, where the plugin (for Bluetooth, USB, etc.) sends them out to the printer.</p><p>This separation is great for maintainability:</p><ul><li>The Flutter/Dart side deals with formatting (which can be tested on any platform, even in pure Dart unit tests).</li><li>The native side deals with I/O (which is abstracted by plugins, so we rarely write any native code ourselves).</li></ul><h3>Example: End-to-End Thermal Print in Flutter</h3><p>Let’s bring it all together with an end-to-end pseudocode example using a hypothetical unified interface (to keep it succinct):</p><pre>import &#39;package:esc_pos_utils_plus/esc_pos_utils.dart&#39;;<br>import &#39;package:flutter_thermal_printer/flutter_thermal_printer.dart&#39;;<br><br>void printSampleReceipt() async {<br>  // 1. Discover or select printer (Bluetooth in this case)<br>  final printers = await FlutterThermalPrinter.instance.getPrinters(<br>    connectionTypes: [ConnectionType.BLUETOOTH],<br>    refreshDuration: Duration(seconds: 2)<br>  );<br>  if (printers.isEmpty) {<br>    print(&#39;No printers found&#39;);<br>    return;<br>  }<br>  final printer = printers.first;<br>  <br>  // 2. Connect to the printer<br>  bool connected = await FlutterThermalPrinter.instance.connect(printer);<br>  if (!connected) {<br>    print(&#39;Failed to connect to printer&#39;);<br>    return;<br>  }<br>  <br>  // 3. Generate print content (using esc_pos_utils_plus)<br>  final profile = await CapabilityProfile.load();<br>  final generator = Generator(PaperSize.mm58, profile); // example for 58mm printer<br>  List&lt;int&gt; bytes = [];<br>  bytes += generator.text(&#39;FLUTTER POS DEMO&#39;, styles: PosStyles(align: PosAlign.center, bold: true));<br>  bytes += generator.text(&#39;Transaction #12345&#39;, styles: PosStyles(align: PosAlign.center));<br>  bytes += generator.hr();<br>  bytes += generator.text(&#39;Item A    x1    \\$10.00&#39;);<br>  bytes += generator.text(&#39;Item B    x2    \\$5.00&#39;);<br>  bytes += generator.hr();<br>  bytes += generator.text(&#39;TOTAL   \\$20.00&#39;, styles: PosStyles(bold: true));<br>  bytes += generator.feed(1);<br>  bytes += generator.qrcode(&#39;&lt;https://example.com/verify/12345&gt;&#39;);<br>  bytes += generator.cut();<br>  <br>  // 4. Send bytes to printer<br>  await FlutterThermalPrinter.instance.printBytes(bytes);<br>  <br>  // 5. (Optional) Disconnect after printing<br>  await FlutterThermalPrinter.instance.disconnect();<br>}</pre><p>Let’s break down a few important parts of this code:</p><ul><li>We used <strong>flutter_thermal_printer</strong>’s <strong>getPrinters</strong> to scan for Bluetooth printers <a href="https://pub.dev/packages/flutter_thermal_printer">pub.dev</a>. This abstracts the scanning for us (no manual permission juggling).</li><li>We connected to the first found printer. In real apps, you’d present a list to the user.</li><li>We generated a simple ticket with a header, two items, a total, and a QR code. Notice we added some spacing (feed) and cut command, typical for a receipt.</li><li>Finally, we called <strong>printBytes</strong> to actually print, then disconnected.</li></ul><p>Such code would produce a receipt on a 58mm paper roll with centered title, items list, and a QR code. Despite being <em>code-heavy</em>, thanks to Flutter’s rich package ecosystem, it remains quite <strong>readable and high-level</strong> (no dealing with hex bytes manually or writing native code for Bluetooth).</p><h3>Wrapping Up: Flutter + ESC/POS = 💙</h3><p>Flutter’s ability to <strong>harmonize UI and hardware control</strong> is what makes it an excellent choice for kiosk and POS applications with thermal printers. Key takeaways:</p><ul><li><strong>Unified Development:</strong> One app can run on multiple device types (from mobile phones to embedded kiosks) and handle printing uniformly.</li><li><strong>Powerful Packages:</strong> The combination of <strong>esc_pos_utils_plus</strong> for formatting and various printer plugins for connectivity covers virtually all ESC/POS scenarios (text, images, barcodes, multiple connection types).</li><li><strong>Real-world Proven:</strong> Deployments like payment kiosks show that Flutter can deliver industrial-grade reliability for printing receipts in production environments.</li><li><strong>Developer Friendly:</strong> With hot reload for UI tweaks and high-level APIs for printing, developers can iterate quickly on the look and content of printed receipts, which is crucial for customer-facing systems.</li><li><strong>Community &amp; Support:</strong> A vibrant community means continuous improvements. For instance, ESC/POS packages are updated to support new frameworks (Dart 3 compatibility, etc.) and new plugins emerge to simplify integration (like unified thermal printer services).</li></ul><p>By choosing Flutter for your kiosk or POS printer integration, you’re investing in a future-proof solution that delights both developers (for its simplicity) and end-users (for its seamlessness). Whether you’re printing a shopping receipt, a ticket, or a payment confirmation, Flutter’s got you covered — <em>fast, beautifully, and everywhere</em>.</p><h3>About ICEFelix</h3><p><strong>ICEFELIX.com</strong> continues Romania’s legacy of engineering excellence by creating practical, scalable solutions at the intersection of software and hardware. We specialize in Flutter-powered kiosk interfaces, embedded systems, and POS automation — focusing on performance, maintainability, and real-world deployment.</p><p>If you’re working on a project that requires reliable device integration or cross-platform printing, we’re available to collaborate with clarity and precision.</p><p>📩 Reach out directly at <strong>contact@icefelix.com</strong> for technical discussions or partnership opportunities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bf21224c613" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Role and Permission Management in Supabase: Enhancing Security and Flexibility]]></title>
            <link>https://medium.com/@alex.bordei1991/dynamic-role-and-permission-management-in-supabase-enhancing-security-and-flexibility-3062794b2129?source=rss-66ccae38d2d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/3062794b2129</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-supabase]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[supabase]]></category>
            <dc:creator><![CDATA[Alex Bordei   ]]></dc:creator>
            <pubDate>Sun, 17 Mar 2024 08:04:47 GMT</pubDate>
            <atom:updated>2024-03-17T08:07:08.626Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p><strong>Supabase</strong> shines as an outstanding cloud backend solution, positioning itself as a strong Firebase alternative. At its heart, Supabase embraces the power of <strong>PostgreSQL</strong>, wrapping its capabilities in a cloud-friendly package. This combination brings the best of relational databases — robust, scalable, and versatile — right to the fingertips of developers, with an added layer of convenience.</p><p>What makes <strong>Supabase</strong> particularly attractive is its offer of self-hosting. This feature hands control back to the developers, allowing them to steer their deployment strategies as needed. Starting is cost-free, and the platform scales economically, making it a viable option for projects big and small.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xsq8erTQBcP9SlDYorScbw.png" /></figure><h3>Key Features of Supabase:</h3><ul><li><strong>Remote Procedure Calls (RPC):</strong> These simplify the execution of functions directly within the database, enabling straightforward handling of complex operations.</li><li><strong>Cloud Functions:</strong> Enhance your app’s capabilities with functions that trigger in response to database events or API requests, extending functionality without the server overhead.</li><li><strong>Database Management:</strong> Supabase provides a fully managed PostgreSQL experience, supporting intricate queries, relationships, and smooth migrations.</li><li><strong>Authentication Methods:</strong> It offers a broad spectrum of authentication options, from social logins to email/password combos, fortified with built-in security measures.</li><li><strong>Storage Management: </strong>This feature allows for efficient file storage handling, catering to diverse needs — from user-generated content to essential app assets.</li><li><strong>Libraries and SDKs:</strong> A rich ecosystem of libraries enables seamless Supabase integration, boosting developer productivity significantly.</li><li><strong>Extensive Documentation: </strong>From setup to advanced operations, Supabase’s documentation is thorough, ensuring developers have the support they need at every step.</li><li><strong>Logs and Monitoring:</strong> Real-time logging and monitoring tools provide insight into your application’s performance and activities, helping you stay informed and proactive.</li><li><strong>Real-time Database:</strong> Implement real-time functionalities effortlessly, allowing applications to react immediately to data changes.</li></ul><p>Choosing <strong>Supabase</strong> for <strong>Flutter</strong>-based projects was a no-brainer for me. Its integration with <strong>Flutter</strong> is flawless, enhancing the development process and allowing for the quick, efficient creation of feature-rich applications. Whether you’re crafting dynamic web apps or sophisticated mobile apps, <strong>Supabase</strong> stands ready as a robust, adaptable platform.</p><p>Managing <strong>roles</strong> and <strong>permissions</strong> is fundamental to both security and operational efficiency in any application. Supabase elevates this with <strong>PostgreSQL’s</strong> row-level security (<strong>RLS</strong>) and customizable policies, granting developers precise control over data access. This capability is crucial for building secure, personalized user experiences with minimal hassle. It’s not just about <strong>security</strong>; it’s about streamlining interactions and bolstering the backend’s robustness for modern applications.</p><h3>Pain Points</h3><p>Supabase introduces a set of <strong>RPCs</strong> for managing user roles and permissions, which is a step in the right direction. However, developers often encounter limitations that can hinder the flexibility and dynamism needed for modern applications.</p><p>One significant issue is the lack of dynamic updates to user roles and permissions. When a user’s role is assigned or updated, it doesn’t automatically reflect in their session. This lack of immediacy can disrupt the user experience, sometimes requiring a logout and login to reset session data.</p><p>Furthermore, <strong>Supabase’s</strong> system primarily handles roles, not permissions. This distinction means there’s no straightforward way to specify varied access levels for different users directly.</p><p>For example, if one user needs to read from a database table and another user requires both read and insert permissions, this differentiation demands a slew of custom policies under the current role-level security (<strong>RLS</strong>) and policy management framework.</p><p>Essentially, for each role added — be it ‘client’ for read-only access or ‘admin’ for read and insert permissions — every table in the database needs updating to recognize these roles, compounding the workload with each new role created.</p><p>This cumbersome process highlights the need for a simpler, more efficient way to manage access. Ideally, a straightforward <strong>RPC</strong> could determine whether an authenticated user has the necessary permissions for a given action, boiling down the decision to a simple true/false output.</p><h3>The Solution</h3><p>My approach builds on the existing framework proposed by the <strong>Supabase</strong> <strong>community</strong> for managing custom claims, enhancing it without making foundational changes. A great starting point for implementing this enhanced approach is the install.sql script available in the <strong>Supabase</strong> <strong>community&#39;s</strong> <strong>GitHub</strong> <strong>repository</strong>. Running this script in the <strong>Supabase</strong> <strong>SQL</strong> <strong>editor</strong> lays the groundwork for the subsequent steps.</p><p><a href="https://github.com/supabase-community/supabase-custom-claims/blob/main/install.sql">Supabase Custom Claims Installation Script</a></p><p>For more detailed information, refer to the <a href="https://github.com/supabase-community/supabase-custom-claims/tree/main">Supabase Custom Claims GitHub page</a>.</p><h3>Now the custimozation part</h3><p>The first step in this dinamization process is to create a dedicated table for managing roles within <strong>Supabase</strong>. This roles table is designed to simplify the process of role management, making it more intuitive and less cumbersome for developers to handle role assignments and modifications.</p><pre>create table<br>  public.roles (<br>    id serial,<br>    name text not null,<br>    constraint roles_pkey primary key (id),<br>    constraint roles_name_key unique (name)<br>  ) tablespace pg_default;</pre><p>In enhancing the role and permission management in <strong>Supabase</strong>, let’s dive into the next critical component of the solution: the <strong>permissions</strong> table.</p><pre>create table<br>  public.permissions (<br>    id serial,<br>    role_id integer null,<br>    table_name text null,<br>    actions text null,<br>    constraint permissions_pkey primary key (id),<br>    constraint unique_role_table unique (role_id, table_name),<br>    constraint permissions_role_id_fkey foreign key (role_id) references roles (id)<br>  ) tablespace pg_default;</pre><p>Next, we’ll develop a database function tailored for verifying whether a user’s role grants them the necessary permission for a specific action. This function taps into the user’s role, as indicated in their <strong>JWT</strong> claims, to perform this check efficiently.</p><pre>CREATE OR REPLACE FUNCTION check_user_permission_with_claims(table_name text, action_required text)<br>RETURNS boolean AS $$<br>DECLARE<br>    user_role TEXT;<br>    has_permission BOOLEAN;<br>BEGIN<br>    -- Extract the user&#39;s role from the JWT claims<br>    user_role := current_setting(&#39;request.jwt.claims&#39;, true)::jsonb-&gt;&#39;app_metadata&#39;-&gt;&gt;&#39;userrole&#39;;<br>    <br>    -- Dynamically check permissions based on extracted user_role, table_name, and action_required<br>    EXECUTE format(&#39;SELECT EXISTS (<br>                        SELECT 1<br>                        FROM permissions p<br>                        JOIN roles r ON p.role_id = r.id<br>                        WHERE r.name = %L<br>                        AND p.table_name = %L<br>                        AND (p.actions = %L OR p.actions = &#39;&#39;*&#39;&#39;)<br>                    )&#39;, user_role, table_name, action_required) INTO has_permission;<br>RETURN has_permission;<br>END;<br>$$ LANGUAGE plpgsql SECURITY DEFINER;</pre><p>By employing this method, we streamline the process, enabling the use of four universal policies for various <strong><em>actions — select, insert, update, and delete</em></strong> — across database tables or during policy validation. This approach significantly reduces complexity, eliminating the need to create individual policies for each role.</p><pre>check_user_permission_with_claims(&#39;categories&#39;::text, &#39;r&#39;::text) -- SELECT<br>check_user_permission_with_claims(&#39;categories&#39;::text, &#39;i&#39;::text) -- INSERT<br>check_user_permission_with_claims(&#39;categories&#39;::text, &#39;u&#39;::text) -- UPDATE<br>check_user_permission_with_claims(&#39;categories&#39;::text, &#39;d&#39;::text) -- DELETE</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*1x2tfi26exRRqNQKDG1JBg.png" /></figure><p>This approach simplifies access control by allowing the addition of broad verification policies for user access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cgV9Q-uegr3e0SRNYHRexQ.png" /></figure><p>To make the process of adding these policies even smoother, let’s introduce a function specifically designed for this task.</p><pre>CREATE OR REPLACE FUNCTION add_policy_to_authenticated_users(table_name text, permission_type text)<br>RETURNS void AS $$<br>DECLARE<br>    policy_name text;<br>    policy_command text;<br>BEGIN<br>    -- Determine the policy name and policy command based on the permission type<br>    CASE permission_type<br>        WHEN &#39;SELECT&#39; THEN<br>            policy_name := table_name || &#39;.select&#39;;<br>            policy_command := format(&#39;CREATE POLICY %I ON %I FOR SELECT TO authenticated USING (check_user_permission_with_claims(%L, &#39;&#39;r&#39;&#39;))&#39;, policy_name, table_name, table_name);<br>        WHEN &#39;INSERT&#39; THEN<br>            policy_name := table_name || &#39;.insert&#39;;<br>            policy_command := format(&#39;CREATE POLICY %I ON %I FOR INSERT TO authenticated WITH CHECK (check_user_permission_with_claims(%L, &#39;&#39;i&#39;&#39;))&#39;, policy_name, table_name, table_name);<br>        WHEN &#39;UPDATE&#39; THEN<br>            policy_name := table_name || &#39;.update&#39;;<br>            policy_command := format(&#39;CREATE POLICY %I ON %I FOR UPDATE TO authenticated USING (check_user_permission_with_claims(%L, &#39;&#39;u&#39;&#39;))&#39;, policy_name, table_name, table_name);<br>        WHEN &#39;DELETE&#39; THEN<br>            policy_name := table_name || &#39;.delete&#39;;<br>            policy_command := format(&#39;CREATE POLICY %I ON %I FOR DELETE TO authenticated USING (check_user_permission_with_claims(%L, &#39;&#39;d&#39;&#39;))&#39;, policy_name, table_name, table_name);<br>        ELSE<br>            RAISE EXCEPTION &#39;Unsupported permission type: %&#39;, permission_type;<br>    END CASE;<br><br>    -- Enable Row-Level Security on the table if not already enabled<br>    EXECUTE format(&#39;ALTER TABLE %I ENABLE ROW LEVEL SECURITY&#39;, table_name);<br><br>    -- Apply the policy to the table<br>    EXECUTE policy_command;<br>END;<br>$$ LANGUAGE plpgsql SECURITY DEFINER;</pre><p>I’ve also devised a concise query to expedite the process of applying general policies to the tables.</p><pre>do $$<br>DECLARE<br>    table_name text := &#39;products&#39;;<br>    dummy_variable text;<br>BEGIN<br>    select add_policy_to_authenticated_users(table_name, &#39;SELECT&#39;) into dummy_variable;<br>    select add_policy_to_authenticated_users(table_name, &#39;INSERT&#39;) into dummy_variable;<br>    select add_policy_to_authenticated_users(table_name, &#39;UPDATE&#39;) into dummy_variable;<br>    select add_policy_to_authenticated_users(table_name, &#39;DELETE&#39;) into dummy_variable;<br>END $$;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*VMEr-mVVLMqXuZ_tdig27Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dZVpuPWCzT9PWB-o7CAbLw.png" /></figure><p>This way, by just managing the roles and <strong>permissions</strong> table data with using set_claim and get_claim methods from Supabase claims management proposal, we don’t need to separatelly manage each policy for each <strong>userrole</strong> and <strong>permission</strong> type on each table.</p><h3>EXTRA</h3><p>The check_user_permission_with_claims method can be used also in for database functions access management, like this:</p><pre>    IF NOT check_user_permission_with_claims(&#39;functions.get_categories&#39;, &#39;r&#39;) THEN<br>        RAISE EXCEPTION &#39;User does not have permission to fetch categories.&#39;;<br>    END IF;</pre><p>Example of a complete query</p><pre><br>BEGIN<br>    -- Check user permission<br>    IF NOT check_user_permission_with_claims(&#39;functions.get_categories&#39;, &#39;r&#39;) THEN<br>        RAISE EXCEPTION &#39;User does not have permission to fetch categories.&#39;;<br>    END IF;<br><br>    -- If permission check passes, execute the query<br>    RETURN QUERY SELECT<br>        c.id,<br>        c.name::TEXT,<br>        c.description,<br>        c.parent_id,<br>        c.featured,<br>        c.status::TEXT as status,<br>        c.disabled_reason,<br>        c.image_id,<br>        pc.name::TEXT AS parent_category_name,<br>        i.name::TEXT AS image_url <br>    FROM<br>        categories c<br>        LEFT JOIN categories pc ON c.parent_id = pc.id<br>        LEFT JOIN storage.objects i ON c.image_id = i.id<br>    WHERE<br>        c.deleted_at IS NULL;<br><br>END;</pre><h3>Concluding Thoughts</h3><p>This method revolutionizes how user roles and permissions are handled, transitioning to a dynamic management system. By implementing a universal permission rule, denoted as “*”, we can streamline access across all actions — <strong><em>be it reading, inserting, updating, or deleting</em></strong>. For instance, assigning the permission to an admin role effectively grants it comprehensive access across the board, simplifying policy assignments tremendously.</p><p>Moreover, this approach enables the external management of roles and permissions. There’s no longer a necessity to log directly into Supabase for these tasks. Through the use of set_claim and the strategic insertion of roles and permissions into their respective tables, new roles can seamlessly integrate with existing policies. This significantly reduces the administrative overhead, making it easier to adapt and scale permissions without altering the fundamental policy configurations on the tables.</p><p>In essence, this strategy not only makes managing roles and permissions more efficient but also ensures a level of flexibility and scalability previously unattainable, paving the way for more secure and adaptable applications.</p><h3>Connect and Share</h3><p>If you’ve found this guide helpful or wish to discuss it further, I’d love to connect! You can find me on Instagram as @alexbordei, on Twitter @abordei, or visit my website at <a href="http://alexbordei.dev/">alexbordei.dev</a>.</p><p>I hope you’ve enjoyed this walkthrough and found it valuable. If so, please feel free to share it with others who might also benefit.</p><p><strong>Alex Bordei </strong>💙<br><strong><em>Organizer of the Flutter Bucharest Meetup, Flutter Speaker<br>Full-Stack Flutter Developer</em></strong></p><p>Your support and feedback mean the world to me, and I’m eager to hear your thoughts or see how you implement these solutions in your own projects!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3062794b2129" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter dark/light theme switcher with BLoC]]></title>
            <link>https://medium.com/@alex.bordei1991/flutter-dark-light-theme-switcher-with-bloc-edd260b45768?source=rss-66ccae38d2d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/edd260b45768</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[Alex Bordei   ]]></dc:creator>
            <pubDate>Sat, 24 Dec 2022 10:14:33 GMT</pubDate>
            <atom:updated>2023-01-05T13:24:13.833Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, Flutter-interested buddy.</p><p>I find this article handy for beginners that just need some boost to implement something that seems to have so many approaches in the development industry.</p><p>Today I will be writing about how the BLoC paradigm can be used for obtaining a global way to switch your application theme mode from light to dark by just using a simple switch component.</p><p>First of all, to be able to follow this article you need to already know Flutter basics and BLoC.</p><p>For more information about BLoC, I truly recommend <a href="https://medium.com/u/4a9e97793c8a">Ana Polo</a>’s article about <strong><em>Flutter BLoc for Beginners</em></strong>, here: <a href="https://medium.com/flutter-community/flutter-bloc-for-beginners-839e22adb9f5">https://medium.com/flutter-community/flutter-bloc-for-beginners-839e22adb9f5</a> (Ana, thank you for your article).</p><p>We gonna create a new Flutter project and dive into our application folder.</p><pre>flutter create theme_switcher<br>cd theme_switcher</pre><p>Now, let’s open the project.</p><p>I am using Visual Studio code for developing my Flutter projects but feel free to open your project in any supported IDE that you like.</p><pre>code .</pre><p>You can open your project files directly using the terminal by configuring the bash command code from Visual Studio Code.</p><p>More about this here: <a href="https://code.visualstudio.com/docs/setup/mac">https://code.visualstudio.com/docs/setup/mac</a></p><p>Now, let’s create and configure our light-dark theme files and setup them up properly with our application.</p><p>I personally prefer to organise my application themes into a particular themes folder in which I am creating my theme-related classes both for the dark or light modes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*pyER3nALGDC6OicXTe06og.png" /></figure><p>Next, I am creating the theme configuration by adding two ThemeData static properties with the customisation I want for each theme.</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>class DefaultTheme {<br>  static final ThemeData _defaultTheme = ThemeData(<br>    // Define the default font family.<br>    fontFamily: &#39;Georgia&#39;,<br><br>    // Define the default `TextTheme`. Use this to specify the default<br>    // text styling for headlines, titles, bodies of text, and more.<br>    textTheme: const TextTheme(<br>      displayLarge: TextStyle(fontSize: 72.0, fontWeight: FontWeight.bold),<br>      titleLarge: TextStyle(fontSize: 36.0, fontStyle: FontStyle.italic),<br>      bodyMedium: TextStyle(fontSize: 14.0, fontFamily: &#39;Hind&#39;),<br>    ),<br>  );<br><br>  static ThemeData light = _defaultTheme.copyWith(<br>    primaryColor: Colors.lightBlue,<br>    scaffoldBackgroundColor: Colors.white,<br>  );<br><br>  static ThemeData dark = _defaultTheme.copyWith(<br>    brightness: Brightness.dark,<br>    primaryColor: Colors.blueGrey,<br>    scaffoldBackgroundColor: Colors.grey,<br>  );<br>}</pre><p>As we can see in the example above, both light and dark properties are based on the private _defaultTheme main configuration, but slightly different values for properties, like for primaryColor, scaffoldBckgroundColor or brightness .</p><p>Now, let’s provide our theme configuration for the application that we are writing.</p><p>For this to happen, it is necessary to configure our MaterialApp instance properties to have your theme configuration values.</p><pre>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;Flutter Demo&#39;,<br>      theme: DefaultTheme.light,<br>      darkTheme: DefaultTheme.dark,<br>      themeMode: ThemeMode.light,<br>      home: const MyHomePage(title: &#39;Flutter Demo Home Page&#39;),<br>    );<br>  }<br>}</pre><p>Also, we preconfigured the themeMode value to be ThemeMode.light and as a spoiler alert, this will be the spot in which our BloC dynamisation will be inserted.</p><p>You can try to switch themeMode to ThemeMode.dark or ThemeMode.light in order to see what is happening but for now the changes will be available just after hot reload or hot restart .</p><p>Let’s add some BloC magic next for making this theme BloC-based switcher dream a reality. 💙</p><p>First, we gonna install the flutter_bloc: ^8.1.1 package by adding the name of the package that we want to use and the versions that we want to use in present and future, into pubspec.yaml file into the dependencies: section.</p><pre>dependencies:<br>  cupertino_icons: ^1.0.2<br>  flutter:<br>    sdk: flutter<br>  flutter_bloc: ^8.1.1</pre><p>Now, because we installed BloC into our application let’s actually create the BloC for our theme switcher.</p><p>I am doing this by using the BloC Visual Studio Package in order to create a new BloC implementation in the themes folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*goS_7X4WYEoOEigOQDJxIQ.png" /></figure><p>I will name the BloC as theme_switcher</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2lqTExI6i_a8ty1RD5H0Ug.png" /></figure><p>I renamed the bloc folder to theme_switcher and this is the configuration that resulted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*ia3KbP7xy8Sm-Yxy88Laqg.png" /></figure><p>Ok. Let’s think a little. BloC is managing events and states and by this, we gonna have the following use-case.</p><p>We have two possible states: themeIsLight and themeIsDark</p><p>And for changing the states we gonna send two different events: switchThemeToLight and switchThemeToDark</p><p>Also, we gonna focus on being able to get the themeMode state at any point in the application by looking after it in the application context.</p><p>theme_switcher_state.dart</p><pre>part of &#39;theme_switcher_bloc.dart&#39;;<br><br>@immutable<br>abstract class ThemeSwitcherState {<br>  abstract final ThemeMode themeMode;<br>}<br><br>class InitialThemeMode extends ThemeSwitcherState {<br>  @override<br>  final ThemeMode themeMode;<br><br>  InitialThemeMode(this.themeMode);<br>}<br><br>class ThemeIsLight extends ThemeSwitcherState {<br>  @override<br>  final ThemeMode themeMode = ThemeMode.light;<br>}<br><br>class ThemeIsDark extends ThemeSwitcherState {<br>  @override<br>  final ThemeMode themeMode = ThemeMode.dark;<br>}</pre><p>We added an abstract property called themeMode in order to change its value through the classes that are extending out ThemeSwitcherState and also you can observe an InitialThemeMode that is receiving a ThemeMode parameter for its constructor in order to let us set up the initial ThemeMode when declaring the BloC instance.</p><p>theme_switcher_event.dart</p><pre>part of &#39;theme_switcher_bloc.dart&#39;;<br><br>@immutable<br>abstract class ThemeSwitcherEvent {}<br><br><br>class SwitchThemeToLight extends ThemeSwitcherEvent {}<br><br>class SwitchThemeToDark extends ThemeSwitcherEvent {}</pre><p>Please observe above the two events created.</p><p>theme_switcher_bloc.dart</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br><br>part &#39;theme_switcher_event.dart&#39;;<br>part &#39;theme_switcher_state.dart&#39;;<br><br>class ThemeSwitcherBloc extends Bloc&lt;ThemeSwitcherEvent, ThemeSwitcherState&gt; {<br>  ThemeSwitcherBloc(ThemeMode themeMode) : super(InitialThemeMode(themeMode)) {<br>    on&lt;SwitchThemeToLight&gt;((event, emit) {<br>      emit(<br>        ThemeIsLight(),<br>      );<br>    });<br><br>    on&lt;SwitchThemeToDark&gt;((event, emit) {<br>      emit(<br>        ThemeIsDark(),<br>      );<br>    });<br>  }<br>}</pre><p>In our BloC object, we link ourevents with specific states .</p><p>We are very close to finishing this tutorial and also we ready to use the ThemeSwitcherBloc so let’s go on and provide our ThemeSwitcherBloc to the entire widget tree of our application.</p><p>First of all, we gonna wrap MaterialStateApp in a BlocProviderInstance</p><pre>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return BlocProvider(<br>      create: (context) =&gt; ThemeSwitcherBloc(ThemeMode.light),<br>      child: MaterialApp(<br>        title: &#39;Flutter Demo&#39;,<br>        theme: DefaultTheme.light,<br>        darkTheme: DefaultTheme.dark,<br>        themeMode: ThemeMode.light,<br>        home: const MyHomePage(title: &#39;Flutter Demo Home Page&#39;),<br>      ),<br>    );<br>  }<br>}</pre><p>Because this way we provided our BloC to the widget tree, now we need to use it for our themeMode property. For this to happen, we gonna wrap MaterialApp in a BlocBuilder instance and then change the themeMode property value to state.ThemeMode provided by BloC.</p><pre>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return BlocProvider(<br>      create: (context) =&gt; ThemeSwitcherBloc(ThemeMode.light),<br>      child: BlocBuilder&lt;ThemeSwitcherBloc, ThemeSwitcherState&gt;(<br>        builder: (context, state) {<br>          return MaterialApp(<br>            title: &#39;Flutter Demo&#39;,<br>            theme: DefaultTheme.light,<br>            darkTheme: DefaultTheme.dark,<br>            themeMode: state.themeMode,<br>            home: const MyHomePage(title: &#39;Flutter Demo Home Page&#39;),<br>          );<br>        },<br>      ),<br>    );<br>  }<br>}</pre><p>Now, let’s consume our implementation by creating a Theme Switch component and using it in our application.</p><p>I am creating a new theme_switch.dart file into a new folder called components , like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*a8QbvoQsG5WpP2O7cxAwGw.png" /></figure><p>theme_switch.dart</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br><br>import &#39;../themes/theme_switcher/theme_switcher_bloc.dart&#39;;<br><br>class ThemeSwitch extends StatelessWidget {<br>  String title;<br>  ThemeSwitch({<br>    Key? key,<br>    required this.title,<br>  }) : super(key: key);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    final ThemeMode themeMode =<br>        context.watch&lt;ThemeSwitcherBloc&gt;().state.themeMode;<br><br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(title),<br>      ),<br>      body: Column(<br>        mainAxisAlignment: MainAxisAlignment.center,<br>        children: [<br>          Switch(<br>            onChanged: (bool value) {<br>              context.read&lt;ThemeSwitcherBloc&gt;().add(<br>                    themeMode == ThemeMode.light<br>                        ? SwitchThemeToDark()<br>                        : SwitchThemeToLight(),<br>                  );<br>            },<br>            value: themeMode == ThemeMode.light ? false : true,<br>          ),<br>          Text(<br>            &#39;Theme is ${themeMode == ThemeMode.light ? &quot;Light&quot; : &quot;Dark&quot;}&#39;,<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><p>This component is built by a Switch and a Text widgets that are reacting to the general ThemeSwitcherBloc.state.themeMode property.</p><p>Also, the onChanged the method is adding theThemeSwitcherEvents to the BloC in order to change the ThemeSwitcherStates .</p><p>Let’s use this newly created component into MyHomePage and see what is happening.</p><p>main.dart</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br>import &#39;package:theme_switcher/components/theme_switch.dart&#39;;<br><br>import &#39;package:theme_switcher/themes/default_theme.dart&#39;;<br>import &#39;package:theme_switcher/themes/theme_switcher/theme_switcher_bloc.dart&#39;;<br><br>void main() {<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return BlocProvider(<br>      create: (_) =&gt; ThemeSwitcherBloc(ThemeMode.light),<br>      child: BlocBuilder&lt;ThemeSwitcherBloc, ThemeSwitcherState&gt;(<br>        builder: (context, state) {<br>          return MaterialApp(<br>            title: &#39;Flutter Demo&#39;,<br>            theme: DefaultTheme.light,<br>            darkTheme: DefaultTheme.dark,<br>            themeMode: state.themeMode,<br>            home: MyHomePage(title: &#39;Flutter Demo Home Page&#39;),<br>          );<br>        },<br>      ),<br>    );<br>  }<br>}<br><br>class MyHomePage extends StatelessWidget {<br>  final String title;<br>  MyHomePage({<br>    Key? key,<br>    required this.title,<br>  }) : super(key: key);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(title),<br>      ),<br>      body: Center(<br>        child: ThemeSwitch(),<br>      ),<br>    );<br>  }<br>}</pre><p>And, voila!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*0a_vu3Z9gMJJD4i5c-4ZIA.gif" /></figure><p>Even if I personally think this implementation is more about Cubit than BloC, I wanted to address also this paradigm since I see this topic required all over Flutter communities.</p><p>I hope you found this helpful and handy.</p><p>Follow me for more tutorials like this and Happy coding! 💙💙💙</p><p>All the best,</p><p>Alex Bordei</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edd260b45768" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>