How to Use JavaScript Barcode SDK in AngularDart Project

AngularDart, similar to Angular built with TypeScript, is a web app framework written in Dartlang. It finally compiles to JavaScript.  In this article, I will share how to use Dynamsoft JavaScript Barcode SDK to create a simple web barcode reader app using AngularDart on Windows 10.

Download and Installation

  • Dart SDK
  • Webdev and Stagehand:
    pub global activate webdev
    pub global activate stagehand

Building Web Barcode Reader in AngularDart

Create a new project:

mkdir barcode
cd barcode
stagehand web-angular
pub get

Here is the project view in Visual Studio Code.

AngularDart project

By default, the template contains a to-do list component. It is useless, just delete it. After that, clean up the project:

  1. Open lib/app_component.html to delete <todo-list></todo-list>.
  2. In lib/app_component.dart, remove import ‘src/todo_list/todo_list_component.dart’ and directives: [TodoListComponent].

It is time to write my code. Open web/index.html to include the JS barcode library and add the initialization code:

<!DOCTYPE html>
<html>
  <head>
    <title>barcode</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">
    <link rel="icon" type="image/png" href="favicon.png">
    <img src="loading.gif" style="margin-top:10px" id="anim-loading">
    <script src="https://demo.dynamsoft.com/dbr_wasm/js/dbr-6.4.1.0.min.js"></script>
    <script defer src="main.dart.js"></script>
    <script>
        dynamsoft.dbrEnv = dynamsoft.dbrEnv || {};
        dynamsoft.dbrEnv.resourcesPath = 'https://demo.dynamsoft.com/dbr_wasm/js';
        //https://www.dynamsoft.com/CustomerPortal/Portal/TrialLicense.aspx
        dynamsoft.dbrEnv.licenseKey =
          't0068NQAAAJUlQ1oDc6zPWxOAQWn7kD9EGtgZFIqK/k3ULJC5ccG9Xe/lpVOxod82bm6nXxqQXUpC1zjRXU514mWw9XLE1JM=';
        dynamsoft.dbrEnv.bUseWorker = false;
        dynamsoft.dbrEnv.onAutoLoadWasmSuccess = function() {
          document.getElementById('anim-loading').style.display = 'none';
        };
        dynamsoft.dbrEnv.onAutoLoadWasmError = function(ex) {
          alert(ex);
        };
    </script>
  </head>
  <body>
    <my-app>Loading...</my-app>
  </body>
</html>

Add an HTMLInputElement and an HTMLDivElement to lib/app_component.html:

<h1>{{title}}</h1>
<div>
    <input id="uploadImage" type="file" accept="image/bmp,image/jpeg,image/png,image/gif" (input)="readBarcode()">
</div>
<div><b>Barcode result:</b> <span id='barcodeResults'>{{results}}</span></div>

Now let’s do some tricky things in lib/app_component.dart.

To interop JavaScript with Dart, we can import ‘package:js/js.dart’:

@JS()
library app_component;

import 'package:js/js.dart';

To make the package work, add dependency js: ^0.6.0 in pubspec.yaml:

dependencies:
  angular: ^5.1.0
  angular_components: ^0.10.1
  js: ^0.6.0

Declare the JavaScript barcode class and the decoding method:

import 'dart:js';
import 'dart:html';
import 'dart:convert';

@JS("dynamsoft.BarcodeReader")
class DynamsoftBarcodeReader {
  external factory DynamsoftBarcodeReader();
  external Promise<JsArray> decodeFileInMemory(File file);
}

Initialize the object:

class AppComponent implements OnInit {
  
  final title = 'Angular Dart - Barcode Reader';
  String results = '';
  DynamsoftBarcodeReader reader;

  void ngOnInit() async {
    results = '';
    reader = new DynamsoftBarcodeReader();
  }
}

Create a readBarcode() function binding with the HTMLInputElement:

void readBarcode() {
    InputElement input = document.querySelector('#uploadImage');
    FileList files = input.files;
    File file = files.item(0);

    if (reader != null) {
      reader.decodeFileInMemory(file).then(
        allowInterop(getResults)
      );
    } else {
      results = file.name;
    }
  }

The decodeFileInMemory method returns a Promise object, so we need to declare it as follows:

class Promise<T> {
  external Promise then(Function(T result));
}

The getResults() is a callback function for showing results:

void getResults(JsArray barcodes) {
    int len = barcodes.length;
    var json = jsonDecode(stringify(barcodes));
    var tmp = '';
    for (int i = 0; i < len; i++) {
      tmp += json[i]['BarcodeText'] + '; ';
    }
    
    SpanElement spanElement= document.querySelector('#barcodeResults');
    spanElement.text = tmp;
  }

Run the app:

webdev serve

If the port is unavailable, kill the relevant process:

netstat -aon | findstr 8080
taskkill /f /pid <ProcessID>

AngularDart barcode reader

Source Code

https://github.com/dynamsoft-dbr/javascript-barcode/tree/master/examples/angular-dart