DEV Community

Cover image for qr_gen: a QR code generator for Flutter with a pure-Dart encoder
Abdeldjalil Chougui
Abdeldjalil Chougui

Posted on Originally published at abdeldjalilchougui.biz

qr_gen: a QR code generator for Flutter with a pure-Dart encoder

Showing a QR code is a common need: a ticket, a payment link, a Wi-Fi password, a pairing screen. In Flutter the usual answer has been qr_flutter. Its latest release, 4.1.0, dates from May 2023.

A QR code also looks simpler than it is. Behind the black and white squares there are four encoding modes, forty symbol sizes, four error correction levels, Reed–Solomon codes, eight mask patterns and a scoring rule to pick the best one. A generator can produce a code that scans and still be wasteful: a bigger symbol than needed, or blurry edges on screen because modules do not line up with device pixels.

qr_gen is a maintained QR code generator for Flutter and Dart. The ISO/IEC 18004:2015 encoder is written from the standard in pure Dart, and a widget, a painter with PNG export, and SVG output sit on top of it.

What it does

The encoder

The encoder lives in package:qr_gen/qr_encoder.dart and has no Flutter import, so it runs on a server or in a CLI.

  • All 40 versions. The smallest version that holds the data is picked automatically. You can also fix one, or bound the search with minVersion and maxVersion.
  • Error correction levels L, M, Q and H, named QrEcLevel.low to QrEcLevel.high.
  • Numeric, alphanumeric, byte and Kanji modes.
  • Optimal segmentation. A dynamic program over modes splits the text into segments with the fewest bits, taking into account the count-indicator widths for each version range. A string that mixes digits and letters gets the cheapest mix of modes, not one mode for everything.
  • Text encoding. Byte mode uses ISO-8859-1 when the text allows it. Otherwise it uses UTF-8 and prepends an ECI designator (assignment 26), which tells the reader how to decode the bytes. The designator can be turned off with utf8Eci: false.
  • The rest of the standard. Reed–Solomon error correction over GF(256), block interleaving, all eight mask patterns scored with the four penalty rules, and BCH format and version information.

The output is a QrMatrix: the module grid as booleans (isDark, toRows), plus version, ecLevel and mask. QrMatrix.toSvg() produces an SVG string in pure Dart.

The Flutter side

  • QrImageView is the widget. It takes data, version (null for automatic), errorCorrectionLevel, size, padding, a quiet zone of at least 4 modules, colours, and eye and data-module styles (square, rounded, circle, gap). It also takes an embeddedImage with a size and an option to punch out the modules underneath it, a semanticsLabel and an errorStateBuilder.
  • QrPainter is a CustomPainter with toImage(size) and toImageData(size, format: ImageByteFormat.png) for export.
  • Crisp rendering. Each module is a whole number of device pixels, and square modules are drawn without anti-aliasing, so no seams or grey edges appear between modules. The widget passes the screen's device pixel ratio to the painter.

How to use it

Add it from GitHub:

dependencies:
  qr_gen:
    git: https://github.com/AbdeldjalilChougui/qr_gen
Enter fullscreen mode Exit fullscreen mode

A styled code with a logo in the middle:

import 'package:flutter/material.dart';
import 'package:qr_gen/qr_gen.dart';

class TicketCode extends StatelessWidget {
  const TicketCode({super.key});

  @override
  Widget build(BuildContext context) {
    return QrImageView(
      data: 'https://example.com/tickets/42',
      size: 220,
      errorCorrectionLevel: QrEcLevel.high,
      eyeStyle: const QrEyeStyle(shape: QrModuleShape.rounded),
      dataModuleStyle: const QrDataModuleStyle(shape: QrModuleShape.circle),
      embeddedImage: const AssetImage('assets/logo.png'),
      embeddedImageStyle: const QrEmbeddedImageStyle(size: Size(44, 44)),
      semanticsLabel: 'Ticket 42',
      errorStateBuilder: (context, error) =>
          const Center(child: Text('Too much data for a QR code')),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Export a PNG:

Future<ByteData?> ticketPng() =>
    QrPainter(data: 'https://example.com/tickets/42').toImageData(512);
Enter fullscreen mode Exit fullscreen mode

And the encoder without Flutter:

import 'package:qr_gen/qr_encoder.dart';

void main() {
  final qr = QrEncoder.encode('HELLO WORLD', ecLevel: QrEcLevel.quartile);
  print('version ${qr.version}, mask ${qr.mask}, ${qr.size}x${qr.size}');
  print(qr.isDark(0, 0)); // true: top-left finder pattern
  final svg = qr.toSvg(moduleSize: 10);
  print(svg.length);
}
Enter fullscreen mode Exit fullscreen mode

Other entry points are QrEncoder.encodeBytes(bytes), QrEncoder.encodeSegments([...]) for full control over the segments, and QrEncoder.minimumVersion(text). When the data does not fit, a QrDataTooLongException is thrown. It reports bitsNeeded and bitsAvailable.

Migrating from qr_flutter

Most of the API maps one to one, and the README has the full table. QrImageView(data: ...) stays as it is. QrVersions.auto becomes version: null, which is the default. The levels QrErrorCorrectLevel.L / M / Q / H become QrEcLevel.low / medium / quartile / high. gapless: false becomes QrModuleShape.gap, and QrImageView.withQr becomes QrImageView.withMatrix.

A few defaults are different, so check them when you migrate:

  • Default error correction level is M, not L. Pass QrEcLevel.low to keep the old density.
  • Default padding is zero, not 10 logical pixels. The quiet zone of 4 modules, required by the standard, is always drawn inside size.
  • Default background is white, not transparent, because the quiet zone must be light for scanners. Pass backgroundColor: null for transparency.
  • Non-Latin-1 text is marked as UTF-8 with an ECI designator. qr_flutter wrote UTF-8 bytes without saying so. If a legacy reader mishandles ECI, pass utf8Eci: false to QrEncoder.encode and use QrImageView.withMatrix.
  • Modules under an embedded image are punched out by default. Either way, use level Q or H with a logo.

Things to know

How it was verified, from the README:

  • Reference symbols, byte for byte. For the ISO/IEC 18004:2015 Annex I example ("01234567", 1-M), the tests check the published data codewords, EC codewords and selected mask. Symbols generated with qrencode 4.1.1 are stored as fixtures, and the tests check that qr_gen produces the same codewords, the same mask and the same matrix, module for module.
  • Standard tables. For all 160 version and level pairs, capacities and block structure are checked against the ISO tables, along with alignment positions, version information and format information.
  • Round trips. A test-only decoder, written separately from lib/, decodes every version and level, every mask, random mixed-mode text and binary data back to the input.
  • Third-party tools. Local tests, which are not part of CI, decode the output with ZXing and ZBar, compare grids with qrencode, and rasterise the SVG with rsvg-convert. Each group is skipped, with a message, when its tool is not on PATH.

And the limits:

  • Model 2 QR Code only. Micro QR, rMQR, Structured Append and FNC1 (GS1) modes are not implemented.
  • ECI. The only assignment written automatically is 26 (UTF-8). Others can be written with QrSegment.eci(n) in encodeSegments.
  • Kanji mode covers the JIS X 0208 characters on which CPython's shift_jis and cp932 codecs agree. Other characters fall back to byte mode.
  • Mask selection. One penalty rule in the standard leaves room for interpretation. qr_gen's reading reproduces the ISO Annex I choice and matches libqrencode, but other encoders may pick a different mask for the same data. Every mask is valid and decodes the same.
  • Shapes. Rounded and circle shapes are anti-aliased by design. Only the square and gap shapes are guaranteed free of grey pixels.

Why I built it

A QR widget is a small piece of an app, but it is the piece a stranger's camera has to read. I wanted two things from it that I could check, not hope for: the symbol is the one the standard describes, and the pixels on screen are sharp.

Writing the encoder from the standard made the first one testable against published codewords, the ISO tables and independent decoders. Keeping it in pure Dart, apart from the widget, means the same encoder can produce an SVG on a server. And keeping the widget API close to qr_flutter means an existing app can move over with a short list of renames.

Get the code

The source, the migration table, the test fixtures and a runnable example app are on GitHub: https://github.com/AbdeldjalilChougui/qr_gen. It's MIT licensed. Issues and pull requests are welcome.


Originally published at abdeldjalilchougui.biz.

Top comments (0)