Huawei Scan Flutter Plugin

Table of Contents

Introduction

HUAWEI Scan Kit scans and parses all major 1D and 2D barcodes and generates QR codes, helping you quickly build barcode scanning functions into your apps.

Scan Kit automatically detects, magnifies, and recognizes barcodes from a distance, and is also able to scan a very small barcode in the same way. It works even in suboptimal situations, such as under dim lighting or when the barcode is reflective, dirty, blurry, or printed on a cylindrical surface. This leads to a higher scanning success rate, and an improved user experience.

Huawei Scan provides the following basic skills to enable your users to quickly use your scan and barcode creation services:

  • Scan Utils
    • startDefaultView: Brings up Default Scanning UI and returns a response after scanning the barcode using the camera or from gallery.
    • buildBitmap: Returns your own private 1D or 2D barcode that you can create at your request.
    • decodeWithBitmap: Starts bitmap decoding API.
    • enableLogger: This method enables the HMSLogger capability which is used for sending usage analytics of Scan SDK's methods to improve the service quality.
    • disableLogger: This method disables the HMSLogger capability which is used for sending usage analytics of Scan SDK's methods to improve the service quality.
  • Customized View
    • startCustomizedView: Brings up Customized View Scanning UI according to your preferences.
  • Multi Processor
    • startMultiProcessorCamera: Brings up a scanning UI to scan multiple barcodes at the same time according to your preferences.
    • decodeMultiSync: Scans barcodes synchronously in Multi Processor mode.
    • decodeMultiAsync: Scans barcodes asynchronously in MultiProcessor mode.
  • Permissions
    • hasCameraAndStoragePermission: Checks whether your app has camera and storage permissions.
    • requestCameraAndStoragePermissions: Requests camera and storage permissions for your app.

Installation Guide

  • Before you get started, you must register as a HUAWEI developer and complete identity verification on the HUAWEI Developer website. For details, please refer to Register a HUAWEI ID.

  • Create an app in your project is required in AppGallery Connect in order to communicate with Huawei services. To create an app, perform the following steps:

Step 1. Sign in to AppGallery Connect and select My projects.

Step 2. Click your project from the project list.

Step 3. Go to Project Setting > General information, and click Add app. If an app exists in the project, and you need to add a new one, expand the app selection area on the top of the page and click Add app.

Step 4. On the Add app page, enter app information, and click OK.

  • A signing certificate fingerprint is used to verify the authenticity of an app when it attempts to access an HMS Core service through the HMS Core SDK. Before using HMS Core (APK), you must locally generate a signing certificate fingerprint and configure it in AppGallery Connect. Ensure that the JDK has been installed on your computer.

Configuring the Signing Certificate Fingerprint

Step 1: Go to Project Setting > General information. In the App information field, click the icon next to SHA-256 certificate fingerprint, and enter the obtained SHA256 certificate fingerprint.

Step 2: After completing the configuration, click check mark.

Integrating Flutter Scan Plugin

Step 1: Sign in to AppGallery Connect and select My projects.

Step 2: Find your app project, and click the desired app name.

Step 3: Go to Project Setting > General information. In the App information section, click agconnect-service.json to download the configuration file.

Step 4: Create a Flutter project if you do not have one.

Step 5: Copy the agconnect-service.json file to the android/app directory of your Flutter project.

Step 6: Copy the signature file that generated in Generating a Signature File section, to the android/app directory of your Flutter project.

Step 7: Check whether the agconnect-services.json file and signature file are successfully added to the android/app directory of the Flutter project.

Step 8: Open the build.gradle file in the android directory of your Flutter project.

  • Go to buildscript then configure the Maven repository address and agconnect plugin for the HMS SDK.

        buildscript {
            repositories {
                google()
                jcenter()
                maven { url 'https://developer.huawei.com/repo/' }
            }
    
            dependencies {
                /*
                 * <Other dependencies>
                 */
                classpath 'com.huawei.agconnect:agcp:1.4.1.300'
            }
        }
    
  • Go to allprojects then configure the Maven repository address for the HMS SDK.

        allprojects {
            repositories {
                google()
                jcenter()
                maven { url 'https://developer.huawei.com/repo/' }
            }
        }
    

Step 9: Open the build.gradle file in the android/app directory.

  • Add apply plugin: 'com.huawei.agconnect' line after the apply entries.

        apply plugin: 'com.android.application'
        apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
        apply plugin: 'com.huawei.agconnect'
    
  • Set your package name in defaultConfig > applicationId and set minSdkVersion to 19 or higher.

  • Package name must match with the package_name entry in agconnect-services.json file.

        defaultConfig {
                applicationId "<package_name>"
                minSdkVersion 19
                /*
                 * <Other configurations>
                 */
            }
    
  • Copy the signature file that generated in Generating a Signing Certificate to android/app directory.

  • Configure the signature in android according to the signature file information and configure Obfuscation Scripts.

        android {
            /*
             * <Other configurations>
             */
    
            signingConfigs {
                config {
                    storeFile file('<keystore_file>.jks')
                    storePassword '<keystore_password>'
                    keyAlias '<key_alias>'
                    keyPassword '<key_password>'
                }
            }
    
            buildTypes {
                debug {
                    signingConfig signingConfigs.config
                }
                release {
                    minifyEnabled true
                    shrinkResources true
                    proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
                    signingConfig signingConfigs.config
                }
            }
        }
    
  • For Obfuscation Scripts, please refer to Configuring Obfuscation Scripts.

Step 10: On your Flutter project directory find and open your pubspec.yaml file and add library to dependencies.

  • To download the package from pub.dev.

    dependencies:
      huawei_scan: { library version }
    

    or

    If you downloaded the package from the HUAWEI Developer website, specify the library path on your local device.

    dependencies:
      huawei_scan:
        # Replace {library path} with actual library path of Huawei Scan Kit Plugin for Flutter.
        path: { library path }
    
    • Replace {library path} with the actual library path of Flutter Scan Plugin. The following are examples:
      • Relative path example: path: ../huawei_scan
      • Absolute path example: path: D:\Projects\Libraries\huawei_scan

Step 11: Run following command to update package info.

  [project_path]> flutter pub get

Step 12: Run following command to start the app.

  [project_path]> flutter run

API Reference

HmsScanUtils

Contains the methods for starting default view, decoding or building images in bitmap mode.

Public Method Summary

MethodReturn TypeDescription
startDefaultView(DefaultViewRequest request)Future<ScanResponse>Starts the barcode scanning UI of Huawei.
buildBitmap(BuildBitmapRequest request)Future<Image>Generates 1D or 2D barcodes.
decodeWithBitmap(DecodeRequest request)Future<ScanResponse>Bitmap decoding API.
disableLogger()Future<void>Disables HMS Logger.
enableLogger()Future<void>Enables HMS Logger.

Public Methods

Future<ScanResponse> startDefaultView(DefaultViewRequest request) async

Starts the barcode scanning UI of Huawei.

Parameters
NameDescription
requestDefaultViewRequest object
Return Type
Return TypeDescription
Future<ScanResponse>Scanning result of barcode.
Call Example
//Constructing request object.
DefaultViewRequest request = new DefaultViewRequest(scanType:HmsScanTypes.AllScanType);

//Call startDefaultView API with request object.
ScanResponse response = await HmsScanUtils.startDefaultView(request);
Future<Image> buildBitmap(BuildBitmapRequest request) async

Generates 1D or 2D barcodes.

Parameters
NameDescription
requestBuildBitmapRequest object.
Return Type
Return TypeDescription
Future<Image>Created barcode.
Call Example
//Constructing request object.
BuildBitmapRequest request = new BuildBitmapRequest(content: "Content of your barcode");

//Call buildBitmap API with request object.
Image image = await HmsScanUtils.buildBitmap(request);
Future<ScanResponse> decodeWithBitmap(DecodeRequest request) async

Bitmap decoding API.

Parameters
NameDescription
requestDecodeRequest object
Return Type
Return TypeDescription
Future<Image>Created barcode.
Call Example
//Constructing request object.
DecodeRequest request = new DecodeRequest(data: YOUR_BITMAP_DATA, scanType: HmsScanTypes.AllScanType);

//Call decodeWithBitmap API with request object.
ScanResponse response = await HmsScanUtils.decodeWithBitmap(request);
Future<void> disableLogger() async

Disables HMS Logger.

Parameters

None.

Return Type
Return TypeDescription
Future<void>Future result of an execution that returns no value.
Call Example
//Call disableLogger API.
await HmsScanUtils.disableLogger();
Future<void> enableLogger() async

Enables HMS Logger.

Parameters

None.

Return Type
Return TypeDescription
Future<void>Future result of an execution that returns no value.
Call Example
//Call enableLogger API.
await HmsScanUtils.enableLogger();

HmsCustomizedView

Contains the methods for Customized View operations, including starting a camera in Customized View mode.

Public Method Summary

MethodReturn TypeDescription
startCustomizedView(CustomizedViewRequest request)Future<ScanResponse>Controls views of camera preview and barcode scanning in Customized View mode.

Public Methods

Future<ScanResponse> startCustomizedView(CustomizedViewRequest request) async

Controls views of camera preview and barcode scanning in Customized View mode.

Parameters
NameDescription
requestCustomizedViewRequest object
Return Type
Return TypeDescription
Future<ScanResponse>Scanning result of barcode.
Call Example
//Constructing request object.
CustomizedViewRequest request = new CustomizedViewRequest(
     scanType: HmsScanTypes.AllScanType,
);

//Call startCustomizedView API with request object.
ScanResponse response = await HmsCustomizedView.startCustomizedView(request);

HmsMultiProcessor

Contains the methods for starting a camera or decoding an image in Multi Processor modes.

Public Method Summary

MethodReturn TypeDescription
decodeMultiSync(DecodeRequest request)Future<ScanResponseList>Scans barcodes synchronously in MultiProcessor mode.
decodeMultiAsync(DecodeRequest request)Future<ScanResponseList>Scans barcodes asynchronously in MultiProcessor mode.
startMultiProcessorCamera(MultiCameraRequest request)Future<ScanResponseList>Starts multi processor barcode scanning UI of Huawei Flutter Scan Plugin.

Public Methods

Future<ScanResponseList> decodeMultiSync(DecodeRequest request) async

Scans barcodes synchronously in MultiProcessor mode.

Parameters
NameDescription
requestDecodeRequest object
Return Type
Return TypeDescription
Future<ScanResponseList>Scanning results.
Call Example
//Constructing request object.
DecodeRequest request = new DecodeRequest(data: YOUR_BITMAP_DATA, scanType: HmsScanTypes.AllScanType);

//Call decodeMultiSync API with request object.
ScanResponseList response = await HmsMultiProcessor.decodeMultiSync(request);
Future<ScanResponseList> decodeMultiAsync(DecodeRequest request) async

Scans barcodes asynchronously in MultiProcessor mode.

Parameters
NameDescription
requestDecodeRequest object
Return Type
Return TypeDescription
Future<ScanResponseList>Scanning results.
Call Example
//Constructing request object.
DecodeRequest request = new DecodeRequest(data: YOUR_BITMAP_DATA, scanType: HmsScanTypes.AllScanType);

//Call decodeMultiAsync API with request object.
ScanResponseList response = await HmsMultiProcessor.decodeMultiAsync(request);
Future<ScanResponseList> startMultiProcessorCamera(MultiCameraRequest request) async

Starts multi processor barcode scanning UI of Huawei Flutter Scan Plugin.

Parameters
NameDescription
requestMultiCameraRequest object
Return Type
Return TypeDescription
Future<ScanResponseList>Scanning results.
Call Example
//Constructing request object.
MultiCameraRequest request = new MultiCameraRequest(scanType: HmsScanTypes.AllScanType, scanMode: HmsMultiProcessor.MPSyncMode);

//Call startMultiProcessorCamera API with request object.
ScanResponseList response = await HmsMultiProcessor.startMultiProcessorCamera(request);

HmsScanPermissions

Contains the methods for requesting and checking the camera and storage permissions.

Public Method Summary

MethodReturn TypeDescription
hasCameraAndStoragePermission()Future<bool>Checks whether your app has camera and storage permissions.
requestCameraAndStoragePermission()Future<bool>Requests camera and storage permissions for your app.

Public Methods

Future<bool> hasCameraAndStoragePermission() async

Checks whether your app has camera and storage permissions.

Parameters

None.

Return Type
Return TypeDescription
Future<bool>Indicates grant status of permissions.
Call Example
//Call hasCameraAndStoragePermission API.
bool permissionStatus = await HmsScanPermissions.hasCameraAndStoragePermission();
Future<bool> requestCameraAndStoragePermission() async

Requests camera and storage permissions for your app.

Parameters

None.

Return Type
Return TypeDescription
Future<bool>Indicates grant status of permissions.
Call Example
//Call requestCameraAndStoragePermission API.
await HmsScanPermissions.requestCameraAndStoragePermission();

Data Types

Data Types Summary

ClassDescription
AddressInfoObject that contains address details.
HmsBorderRectObject that contains barcode rectangle details.
ContactDetailObject that contains contact details.
CornerPointObject that contains corner point coordinates.
DriverInfoObject that contains driver details.
EmailContentObject that contains email details.
EventInfoObject that contains event details.
EventTimeObject that containt event time details.
LinkUrlObject that contains url details.
LocationCoordinateObject that contains location coordinates.
PeopleNameObject that contains person details.
SmsContentObject that contains sms details.
TelPhoneNumberObject that contains phone number details.
WifiConnectionInfoObject that contains wifi connection details.
ScanResponseInformation returned when the startDefaultView, startCustomizedView and decodeWithBitmap APIs are succesfully called and scanned a barcode.
ScanResponseListInformation returned when the decodeMultiSync, decodeMultiAsync, startCustomizedView and startMultiProcessorCamera APIs are succesfully called and scanned multiple barcodes.
ScanTextOptionsRepresent text options for startMultiProcessorCamera API.
CustomizedViewEventEnumarated object that represents Customized View's lifecycle events.
BuildBitmapRequestRequest information of the buildBitmap API.
CustomizedViewRequestRequest information of the startCustomizedView API.
DecodeRequestRequest information of the decodeWithBitmap, decodeMultiAysnc and decodeMultiSync APIs.
DefaultViewRequestRequest information of the startDefaultView API.
MultiCameraRequestRequest information of the startMultiProcessorCamera API.
HmsScanErrorRepresents an error class for HmsScanErrors.
HmsScanErrorsRepresents error informations including error codes and error messages.
HmsScanFormRepresents scan form types.
HmsScanTypesRepresents barcode types.

AddressInfo

Object that contains address details.

Public Properties
NameTypeDescription
addressDetailsList<String>Address information array.
addressTypeintAddress type.
Public Constants
ConstantsTypeDescription
ResidentialUseTypeintFamily address. Original value: 0
OtherUseTypeintUnknown type. Original value: -1
OfficeTypeintWork address. Original value: 1
Public Constructor Summary
ConstructorDescription
AddressInfo({List<String> addressDetails, int addressType})Default constructor.
AddressInfo.fromJson(String source)Creates an AddressInfo object from a JSON string.
Public Constructors
AddressInfo({List<String> addressDetails, int addressType})

Constructor for AddressInfo object.

ParameterTypeDescription
addressDetailsStringAddress information array.
addressTypeintAddress type.
AddressInfo.fromJson(String source)

Creates an AddressInfo object from JSON String.

ParameterTypeDescription
sourceStringJSON string as a source.

HmsBorderRect

Object that contains barcode rectangle details.

Public Properties
NameTypeDescription
leftintLeft x coordinate.
topintTop y coordinate.
rightintRight x coordinate.
bottomintBottom y coordinate.
exactCenterXdoubleExact value of x coordinate center.
exactCenterYdoubleExact value of y coordinate center.
centerXintRounded value of x coordinate center.
centerYintRounded value of y coordinate center.
Public Constructor Summary
ConstructorDescription
HmsBorderRect({List<CornerPoint> cornerPointsList})Default constructor.
Public Constructors
HmsBorderRect({List<CornerPoint> cornerPointsList})

Constructor for HmsBorderRect object.

ParameterTypeDescription
cornerPointListList<CornerPoint>Corner point list of scanned barcode.

ContactDetail

Object that contains contact details.

Public Properties
PropertiesTypeDescription
addressesInfosList<AddressInfo>Address information.
companyStringCompany information.
contactLinksList<String>URL information.
eMailContentsList<EmailContent>Email content.
noteStringNote.
peopleNamePeopleNameContact information.
telPhoneNumbersList<TelPhoneNumber>Phone number list.
titleStringTitle.
Public Constructor Summary
ConstructorDescription
ContactDetail({List<AddressInfo> addressesInfos, String company, List<String> contacatLinks, List<EmailContent> eMailContents, String note, PeopleName peopleName, List<TelPhoneNumber> telPhoneNumbers, String title})Default constructor.
ContactDetail.fromJson(String source)Creates a ContactDetail object from a JSON string.
Public Constructors

Constructor for ContactDetail object

ParameterTypeDescription
addressesInfosList<AddressInfo>Address information.
companyStringCompany information.
contactLinksList<String>URL information.
eMailContentsList<EmailContent>Email content.
noteStringNote.
peopleNamePeopleNameContact information.
telPhoneNumbersList<TelPhoneNumber>Phone number list.
titleStringTitle.
ContactDetail.fromJson(String source)

Creates a ContactDetail object from a JSON string.

ParameterTypeDescription
sourceStringJSON string as a source.

CornerPoint

Object that contains corner point coordinates.

Public Properties
NameTypeDescription
xintX coordinate.
yintY coordinate.
Public Constructor Summary
ConstructorDescription
CornerPoint({int x, int y})Default constructor.
CornerPoint.fromJson(String source)Creates a CornerPoint object from a JSON string.
Public Constructors
CornerPoint({int x, int y})

Constructor for CornerPoint object.

ParameterTypeDescription
xintX coordinate.
yintY coordinate.
CornerPoint.fromJson(String source)

Creates a CornerPoint object from a JSON string.

ParameterTypeDescription
sourceStringJSON string as a source.

DriverInfo

Object that contains driver details.

Public Properties
NameTypeDescription
avenueStringStreet.
certificateNumberStringDriver license number.
certificateTypeStringDriver license type.
cityStringCity.
countryOfIssueStringCountry where the driver license is issued.
dateOfBirthStringBirth date.
dateOfExpireStringExpiration date of the driver license.
dateOfIssueStringIssue date of the driver license.
familyNameStringLast name.
givenNameStringFirst name.
middleNameStringMiddle name.
provinceStringProvince or state in the address.
sexStringGender.
zipCodeStringZIP code.
Public Constructor Summary
ConstructorDescription
DriverInfo({String avenue, String certificateNumber, String certificateType, String city, String countryOfIssue, String dateOfBirth, String dateOfExpire, String dateOfIssue, String familyName, String givenName, String middleName, String province, String sex, String zipCode})Default constructor.
DriverInfo.fromJson(String source)Creates a DriverInfo object from a JSON string.
Public Constructors
DriverInfo({String avenue, String certificateNumber, String certificateType, String city, String countryOfIssue, String dateOfBirth, String dateOfExpire, String dateOfIssue, String familyName, String givenName, String middleName, String province, String sex, String zipCode})

Constructor for DriverInfo object.

ParameterTypeDescription
avenueStringStreet.
certificateNumberStringDriver license number.
certificateTypeStringDriver license type.
cityStringCity.
countryOfIssueStringCountry where the driver license is issued.
dateOfBirthStringBirth date.
dateOfExpireStringExpiration date of the driver license.
dateOfIssueStringIssue date of the driver license.
familyNameStringLast name.
givenNameStringFirst name.
middleNameStringMiddle name.
provinceStringProvince or state in the address.
sexStringGender.
zipCodeStringZIP code.
DriverInfo.fromJson(String source)

Creates a DriverInfo object from a JSON string.

ParameterTypeDescription
sourceStringJSON string as a source.

EmailContent

Object that contains email details.

Public Properties
NameTypeDescription
addressTypeintEmail address type.
addressInfoStringEmail address.
bodyInfoStringEmail content.
subjectInfoStringSubject of an email.
Public Constants
ConstantsTypeDescription
ResidentialUseTypeintFamily address. Original value: 0
OtherUseTypeintUnknown type. Original value: -1
OfficeTypeintWork address. Original value: 1
Public Constructor Summary
ConstructorDescription
EmailContent({int addressType, String addressInfo, String bodyInfo, String subjectInfo})Default constructor.
EmailContent.fromJson(String source)Creates an EmailContent object from a JSON string.
Public Constructors
EmailContent({int addressType, String addressInfo, String bodyInfo, String subjectInfo})

Constructor for EmailContent object.

ParameterTypeDescription
addressTypeintEmail address type.
addressInfoStringEmail address.
bodyInfoStringEmail content.
subjectInfoStringSubject of an email.
EmailContent.fromJson(String source)

Creates an EmailContent object from JSON String.

ParameterTypeDescription
sourceStringJSON string as a source.

EventInfo

Object that contains event details.

Public Properties
NameTypeDescription
abstractInfoStringCalendar event description.
beginTimeEventTimeStart date of a calendar event.
closeTimeEventTimeEnd date of a calendar event.
conditionStringCalendar event status information.
placeInfoStringCalendar event location information.
sponsorStringCalendar event organizer information.
themeStringCalendar event summary.
Public Constructor Summary
ConstructorDescription
EventInfo({String abstractInfo, EventTime beginTime, EventTime closeTime, String condition, String placeInfo, String sponsor, String theme})Default constructor.
EventInfo.fromJson(String source)Creates an EventInfo object from a JSON string.
Public Constructors
EventInfo({String abstractInfo, EventTime beginTime, EventTime closeTime, String condition, String placeInfo, String sponsor, String theme})

Constructor for EventInfo object.

ParameterTypeDescription
abstractInfoStringCalendar event description.
beginTimeEventTimeStart date of a calendar event.
closeTimeEventTimeEnd date of a calendar event.
conditionStringCalendar event status information.
placeInfoStringCalendar event location information.
sponsorStringCalendar event organizer information.
themeStringCalendar event summary.
EventInfo.fromJson(String source)

Creates an EventInfo object from JSON String.

ParameterTypeDescription
sourceStringJSON string as a source.

EventTime

Object that contains event details.

Public Properties
NameTypeDescription
dayintDay.
hoursintHour.
isUTCTimeboolDetermines whether the time is in UTC format. false: no true: yes
minutesintMinutes.
monthintMonth.
originalValueStringBarcode value.
secondsintSeconds.
yearintYear.
Public Constructor Summary
ConstructorDescription
EventTime({int day, int hours, bool isUTCTime, int minutes, int month, String originalValue, int seconds, int year})Default constructor.
EventTime.fromJson(String source)Creates an EventTime object from a JSON string.
Public Constructors
EventTime({int day, int hours, bool isUTCTime, int minutes, int month, String originalValue, int seconds, int year})

Constructor for EventTime object.

ParameterTypeDescription
dayintDay.
hoursintHour.
isUTCTimeboolDetermines whether the time is in UTC format. false: no true: yes
minutesintMinutes.
monthintMonth.
originalValueStringBarcode value.
secondsintSeconds.
yearintYear.
EventTime.fromJson(String source)

Creates an EventTime object from JSON String.

ParameterTypeDescription
sourceStringJSON string as a source.

LinkUrl

Object that contains url details.

Public Properties
NameTypeDescription
linkvalueStringURL.
themeStringTitle.
Public Constructor Summary
ConstructorDescription
LinkUrl({String linkvalue, String theme})Default constructor.
LinkUrl.fromJson(String source)Creates a LinkUrl object from a JSON string.
Public Constructors
LinkUrl({String linkvalue, String theme})

Constructor for LinkUrl object.

ParameterTypeDescription
linkvalueStringURL.
themeStringTitle.
LinkUrl.fromJson(String source)

Creates an LinkUrl object from JSON String.

ParameterTypeDescription
sourceStringJSON string as a source.

LocationCoordinate

Object that contains location coordinates.

Public Properties
NameTypeDescription
latitudedoubleLatitude.
longitudedoubleLongitude.
Public Constructor Summary
ConstructorDescription
LocationCoordinate({String linkValue, String theme})Default constructor.
LocationCoordinate.fromJson(String source)Creates a LocationCoordinate object from a JSON string.
Public Constructors
LocationCoordinate({String linkValue, String theme})

Constructor for LocationCoordinate object.

ParameterTypeDescription
latitudedoubleLatitude.
longitudedoubleLongitude.
LocationCoordinate.fromJson(String source)

Creates an LocationCoordinate object from JSON String.

ParameterTypeDescription
sourceStringJSON string as a source.

PeopleName

Object that contains person details.

Public Properties
NameTypeDescription
familyNameStringLast name.
fullNameStringFull name of a contact.
givenNameStringFirst name.
middleNameStringMiddle name.
namePrefixStringPrefix of a contact name.
nameSuffixStringSuffix of a contact name.
spellingStringContact name spelling.
Public Constructor Summary
ConstructorDescription
PeopleName({String familyName, String fullName, String givenName, String middleName, String namePrefix, String nameSuffix, String spelling})Default constructor.
PeopleName.fromJson(String source)Creates a PeopleName object from a JSON string.
Public Constructors
PeopleName({String familyName, String fullName, String givenName, String middleName, String namePrefix, String nameSuffix, String spelling})

Constructor for PeopleName object.

ParameterTypeDescription
familyNameStringLast name.
fullNameStringFull name of a contact.
givenNameStringFirst name.
middleNameStringMiddle name.
namePrefixStringPrefix of a contact name.
nameSuffixStringSuffix of a contact name.
spellingStringContact name spelling.
PeopleName.fromJson(String source)

Creates a PeopleName object from JSON String.

ParameterTypeDescription
sourceStringJSON string as a source.

SmsContent

Object that contains sms details.

Public Properties
NameTypeDescription
msgContentStringSMS information.
destPhoneNumberStringPhone number.
Public Constructor Summary
ConstructorDescription
SmsContent({String msgContent, String destPhoneNumber})Default constructor.
SmsContent.fromJson(String source)Creates a SmsContent object from a JSON string.
Public Constructors
SmsContent({String msgContent, String destPhoneNumber})

Constructor for SmsContent object.

ParameterTypeDescription
msgContentStringSMS information.
destPhoneNumberStringPhone number.
SmsContent.fromJson(String source)

Creates a SmsContent object from JSON String.

ParameterTypeDescription
sourceStringJSON string as a source.

TelPhoneNumber

Object that contains phone number details.

Public Properties
NameTypeDescription
telPhoneNumberStringPhone number.
useTypeintPhone number type.
Public Constants
ConstantTypeDescription
FaxUseTypeintFax number. Original value: 0
ResidentialUseTypeintHome phone number. Originalvalue: 1
CellphoneNumberUseTypeintMobile number. Originalvalue: 2
OtherUseTypeintUnknown phone number. Originalvalue: -1
OfficeUseTypeintWork phone number. Originalvalue: 3
Public Constructor Summary
ConstructorDescription
TelPhoneNumber({String telPhoneNumber, int useType})Default constructor.
TelPhoneNumber.fromJson(String source)Creates a TelPhoneNumber object from a JSON string.
Public Constructors
TelPhoneNumber({String telPhoneNumber, int useType})

Constructor for TelPhoneNumber object.

ParameterTypeDescription
telPhoneNumberStringPhone number.
useTypeintPhone number type.
TelPhoneNumber.fromJson(String source)

Creates a TelPhoneNumber object from JSON String.

ParameterTypeDescription
sourceStringJSON string as a source.

WiFiConnectionInfo

Object that contains wifi connection details.

Public Properties
NameTypeDescription
passwordStringWi-Fi password.
ssidNumberStringSSID.
cipherModeintWi-Fi encryption mode.
Public Constants
ConstantTypeDescription
NoPasswordModeTypeintOpen Wi-Fi. Original value: 0
WepModeTypeintWi-Fi in WEP mode. Originalvalue: 1
WpaModeTypeintWi-Fi in WPA mode. Originalvalue: 2
Public Constructor Summary
ConstructorDescription
WiFiConnectionInfo({String password, String ssidNumber, int cipherMode})Default constructor.
WiFiConnectionInfo.fromJson(String source)Creates a WiFiConnectionInfo object from a JSON string.
Public Constructors
WiFiConnectionInfo({String password, String ssidNumber, int cipherMode})

Constructor for WiFiConnectionInfo object.

ParameterTypeDescription
passwordStringWi-Fi password.
ssidNumberStringSSID.
cipherModeintWi-Fi encryption mode.
WiFiConnectionInfo.fromJson(String source)

Creates a WiFiConnectionInfo object from JSON String.

ParameterTypeDescription
sourceStringJSON string as a source.

ScanResponse

Information returned when the startDefaultView, startCustomizedView and decodeWithBitmap APIs are succesfully called.

Public Properties
NameTypeDescription
hmsScanVersionintHMS Scan Version.
cornerPointsList<CornerPoint>Barcode corner point information.
originValueByteList<int>Byte array.
originalValueStringBarcode information.
scanTypeintBarcode format.
scanTypeFormintBarcode content type.
showResultStringBarcode value.
zoomValuedoubleBarcode zoom ratio.
smsContentSmsContentSMS information.
emailContentEmailContentEmail content.
telPhoneNumberTelPhoneNumberPhone number.
linkUrlLinkUrlURL bookmark.
wifiConnectionInfoWiFiConnectionInfoWi-Fi connection info.
locationCoordinateLocationCoordinateLocation information.
driverInfoDriverInfoDriver license information.
contactDetailContactDetailContact information.
eventInfoEventInfoCalendar event.
borderRectHmsBorderRectBarcode rectangle information.
Public Constructor Summary
ConstructorDescription
ScanResponse({int hmsScanVersion, List<CornerPoint> cornerPoints, List<int> originValueByte, String originalValue, int scanType, int scanTypeForm, String showResult, double zomValue, SmsContent smsContent, EmailContent emailContent, TelPhoneNumber telPhoneNumber, LinkUrl linkUrl, WiFiConnectionInfo wifiConnectionInfo, LocationCoordinate locationCoordinate, DriverInfo driverInfo, ContactDetail contactDetail, EventInfo eventInfo})Default constructor.
ScanResponse.fromMap(Map<String, dynamic> map)Creates a ScanResponse object from Map.
ScanResponse.fromJson(String source)Creates a ScanResponse object from a JSON string.
Public Constructors
ScanResponse({int hmsScanVersion, List<CornerPoint> cornerPoints, List<int> originValueByte, String originalValue, int scanType, int scanTypeForm, String showResult, double zomValue, SmsContent smsContent, EmailContent emailContent, TelPhoneNumber telPhoneNumber, LinkUrl linkUrl, WiFiConnectionInfo wifiConnectionInfo, LocationCoordinate locationCoordinate, DriverInfo driverInfo, ContactDetail contactDetail, EventInfo eventInfo})

Constructor for ScanResponse object.

ParameterTypeDescription
hmsScanVersionintHMS Scan Version.
cornerPointsList<CornerPoint>Barcode corner point information.
originValueByteList<int>Byte array.
originalValueStringBarcode information.
scanTypeintBarcode format.
scanTypeFormintBarcode content type.
showResultStringBarcode value.
zoomValuedoubleBarcode zoom ratio.
smsContentSmsContentSMS information.
emailContentEmailContentEmail content.
telPhoneNumberTelPhoneNumberPhone number.
linkUrlLinkUrlURL bookmark.
wifiConnectionInfoWiFiConnectionInfoWi-Fi connection info.
locationCoordinateLocationCoordinateLocation information.
driverInfoDriverInfoDriver license information.
contactDetailContactDetailContact information.
eventInfoEventInfoCalendar event.
ScanResponse.fromMap(Map<String, dynamic> map)

Creates a ScanResponse object from Map.

ParameterTypeDescription
mapMap<String, dynamic>Map as a source.
ScanResponse.fromJson(String source)

Creates a ScanResponse object from a JSON string.

ParameterTypeDescription
mapStringJSON string as a source.

ScanResponseList

Information returned when the decodeMultiSync, decodeMultiAsync and startMultiProcessorCamera APIs are succesfully called.

Public Properties
NameTypeDescription
scanResponseListList<ScanResponse>List of ScanResponse objects.
Public Constructor Summary
ConstructorDescription
ScanResponseList({List<ScanResponse> scanResponseList})Default constructor.
ScanResponseList.fromMap(Map<String, dynamic> map)Creates a ScanResponseList object from Map.
ScanResponseList.fromJson(String source)Creates a ScanResponseList object from a JSON string.
Public Constructors
ScanResponseList({List scanResponseList})

Constructor for ScanResponseList object.

ParameterTypeDescription
scanResponseListList<ScanResponse>List of ScanResponse objects.
ScanResponseList.fromMap(Map<String, dynamic> map)

Creates a ScanResponseList object from Map.

ParameterTypeDescription
mapMap<String, dynamic>Map as a source.
ScanResponseList.fromMap(Map<String, dynamic> map)

Creates a ScanResponseList object from a JSON string.

ParameterTypeDescription
sourceStringJSON string as a source.

ScanTextOptions

Text options for MultiCameraRequest object.

Public Properties
NameTypeDescription
textColorColorText color. Default value: Colors.black
textSizedoubleText size. Default value: 35.0
showTextboolIndicates whether the text is visible. Default value: true
showTextOutBoundsboolIndicates whether to limit the text in rectangle bounds. Default value: false
textBackgroundColorColorText background color. Default value: Colors.transparent
autoSizeTextboolIndicates whether the text auto size itself. Default value: false
minTextSizeintMinimum text size. Default value: 24
granularityintGranularity. Default value: 2
Public Constructor Summary
ConstructorDescription
ScanTextOptions({Color textColor, double textSize, bool showText, bool showTextOutBounds, Color textBackgroundColor, bool autoSizeText, int minTextSize, int granularity})Default constructor.
ScanTextOptions.fromJson(String source)Creates a ScanTextOptions object from a JSON string.
Public Constructors
ScanTextOptions({Color textColor, double textSize, bool showText, bool showTextOutBounds, Color textBackgroundColor, bool autoSizeText, int minTextSize, int granularity})

Constructor for ScanTextOptions object.

ParameterTypeDescription
textColorColorText color. Default value: Colors.black
textSizedoubleText size. Default value: 35.0
showTextboolIndicates whether the text is visible. Default value: true
showTextOutBoundsboolIndicates whether to limit the text in rectangle bounds. Default value: false
textBackgroundColorColorText background color. Default value: Colors.transparent
autoSizeTextboolIndicates whether the text auto size itself. Default value: false
minTextSizeintMinimum text size. Default value: 24
granularityintGranularity. Default value: 2
ScanTextOptions.fromJson(String source)

Creates a ScanTextOptions object from a JSON string.

ParameterTypeDescription
sourceStringJSON string as a source.

CustomizedViewEvent

Enumarated object that represents Customized View's lifecycle events.

Values
NameDescription
onStartCustomized View's onStart function initialized.
onResumeCustomized View's onResume function initialized.
onPauseCustomized View's onPause function initialized.
onDestroyCustomized View's onDestroy function initialized.
onStopCustomized View's onStop function initialized.

BuildBitmapRequest

Request information of the buildBitmap API.

Public Properties
NameTypeDescription
contentStringBarcode content.
typeintBarcode type.
widthintBarcode witdth.
heightintBarcode height.
bitmapColorColorBarcode color.
marginintBarcode margin.
backgroundColorColorBarcode background color.
Public Constructor Summary
ConstructorDescription
BuildBitmapRequest({String content, int type, int width, int height, Color bitmapColor, int margin, Color backgroundColor})Default constructor.
BuildBitmapRequest.fromJson(String source)Creates an BuildBitmapRequest object from a JSON string.
Public Constructors
BuildBitmapRequest({String content, int type, int width, int height, Color bitmapColor, int margin, Color backgroundColor})

Constructor for BuildBitmapRequest object.

ParameterTypeDescription
contentStringBarcode content.
typeintBarcode type.
widthintBarcode witdth.
heightintBarcode height.
bitmapColorColorBarcode color.
marginintBarcode margin.
backgroundColorColorBarcode background color.
BuildBitmapRequest.fromJson(String source)

Creates an BuildBitmapRequest object from JSON String.

ParameterTypeDescription
sourceStringJSON string as a source.

CustomizedViewRequest

Request information of the startCustomizedView API.

Public Properties
NameTypeDescription
scanTypeintBarcode type.
additionalScanTypesList<int>List of additional barcode types.
rectHeightintHeight of scan area.
rectWidthintBarcode height.
flashOnLightChangeboolBarcode color.
isFlashAvailableboolBarcode margin.
isGalleryAvailableboolBarcode background color.
continuouslyScanboolStart customized view in continuous scan mode.
costomizedCameraListenerCustomizedCameraListenerIndicates a function to be performed when a barcode is scanned.
customizedLifeCycleListenerCustomizedLifeCycleListenerIndicates a function to be performed when a barcodes lifecycle changed.
Public Constructor Summary
ConstructorDescription
CustomizedViewRequest({int scanType, List<int> additionalScanTypes, int rectHeight, int rectWidth, bool flashOnLightChange, bool isFlashAvailable, bool isGalleryAvailable, bool continuouslyScan, CustomizedCameraListener customizedCameraListener, CustomizedLifeCycleListener customizedLifeCycleListener})Default constructor.
CustomizedViewRequest.fromJson(String source)Creates an CustomizedViewRequest object from a JSON string.
Public Constructors
CustomizedViewRequest({int scanType, List<int> additionalScanTypes, int rectHeight, int rectWidth, bool flashOnLightChange, bool isFlashAvailable, bool isGalleryAvailable, bool continuouslyScan, CustomizedCameraListener customizedCameraListener, CustomizedLifeCycleListener customizedLifeCycleListener})

Constructor for CustomizedViewRequest object.

ParameterTypeDescription
scanTypeintBarcode type.
additionalScanTypesList<int>List of additional barcode types.
rectHeightintHeight of scan area.
rectWidthintBarcode height.
flashOnLightChangeboolBarcode color.
isFlashAvailableboolBarcode margin.
isGalleryAvailableboolBarcode background color.
continuouslyScanboolStart customized view in continuous scan mode.
costomizedCameraListenerCustomizedCameraListenerIndicates a function to be performed when a barcode is scanned.
customizedLifeCycleListenerCustomizedLifeCycleListenerIndicates a function to be performed when a barcodes lifecycle changed.
CustomizedViewRequest.fromJson(String source)

Creates an CustomizedViewRequest object from JSON String.

ParameterTypeDescription
sourceStringJSON string as a source.

DecodeRequest

Request information of the decodeWithBitmap, decodeMultiSync and decodeMultiAsync APIs.

Public Properties
NameTypeDescription
dataUint8ListUint8List of image.
scanTypeintBarcode type.
additionalScanTypesList<int>List of additional barcode types.
Public Constructor Summary
ConstructorDescription
DecodeRequest({Uint8List data, int scanType, List<int> additionalScanTypes})Default constructor.
DecodeRequest.fromJson(String source)Creates an DecodeRequest object from a JSON string.
Public Constructors
DecodeRequest({Uint8List data, int scanType, List<int> additionalScanTypes})

Constructor for DecodeRequest object.

ParameterTypeDescription
dataUint8ListUint8List of image.
scanTypeintBarcode type.
additionalScanTypesList<int>List of additional barcode types.
DecodeRequest.fromJson(String source)

Creates an DecodeRequest object from JSON String.

ParameterTypeDescription
sourceStringJSON string as a source.

DefaultViewRequest

Request information of the startDefaultView API.

Public Properties
NameTypeDescription
scanTypeintBarcode type.
additionalScanTypesList<int>List of additional barcode types.
Public Constructor Summary
ConstructorDescription
DefaultViewRequest({int scanType, List<int> additionalScanTypes})Default constructor.
DefaultViewRequest.fromJson(String source)Creates an DefaultViewRequest object from a JSON string.
Public Constructors
DefaultViewRequest({int scanType, List<int> additionalScanTypes})

Constructor for DefaultViewRequest object.

NameTypeDescription
scanTypeintBarcode type.
additionalScanTypesList<int>List of additional barcode types.
DefaultViewRequest.fromJson(String source)

Creates an DefaultViewRequest object from JSON String.

ParameterTypeDescription
sourceStringJSON string as a source.

MultiCameraRequest

Request information of the startMultiProcessorCamera API.

Public Properties
NameTypeDescription
scanModeintScan mode.
scanTypeintBarcode type.
additionalScanTypesList<int>List of additional barcode types.
colorListList<Color>Color list.
strokeWidthdoubleStroke width of rectangles.
isGalleryAvailableboolAvailability of gallery button.
multiCameraListenerMultiCameraListenerCamera listener for scan responses.
scanTextOptionsScanTextOptionsText options for Multi Processor Camera.
Public Constructor Summary
ConstructorDescription
MultiCameraRequest({int scanMode, int scanType, List<int> additionalScanTypes, List<Color> colorList, double strokeWidth, bool isGalleryAvailable, MultiCameraListener multiCameraListener, ScanTextOptions scanTextOptions})Default constructor.
MultiCameraRequest.fromJson(String source)Creates an MultiCameraRequest object from a JSON string.
Public Constructors
MultiCameraRequest({int scanMode, int scanType, List<int> additionalScanTypes, List<Color> colorList, double strokeWidth, bool isGalleryAvailable, MultiCameraListener multiCameraListener, ScanTextOptions scanTextOptions})

Constructor for MultiCameraRequest object.

NameTypeDescription
scanModeintScan mode.
scanTypeintBarcode type.
additionalScanTypesList<int>List of additional barcode types.
colorListList<Color>Color list.
strokeWidthdoubleStroke width of rectangles.
isGalleryAvailableboolAvailability of gallery button.
multiCameraListenerMultiCameraListenerCamera listener for scan responses.
scanTextOptionsScanTextOptionsText options for Multi Processor Camera.
MultiCameraRequest.fromJson(String source)

Creates an MultiCameraRequest object from JSON String.

ParameterTypeDescription
sourceStringJSON string as a source.

HmsScanError

Represents an error class for HmsScanErrors.

Public Properties
NameTypeDescription
errorCodeStringError code.
errorMessageStringError message.
Public Constructor Summary
ConstructorDescription
HmsScanError({String errorCode, String errorMessage})Default constructor.
Public Constructors
HmsScanError({String errorCode, String errorMessage})

Constructor for HmsScanError object.

NameTypeDescription
errorCodeStringError code.
errorMessageStringError message.

Constants

HmsScanErrors

ConstantTypeError CodeError MessagePossible Solution
scanUtilNoCameraPermissionHmsScanError1No Camera PermissionCall requestCameraAndStoragePermission API.
scanUtilNoReadPermissionHmsScanError2No Read PermissionCall requestCameraAndStoragePermission API.
decodeMultiAsyncCouldntFindHmsScanError13Multi Async - Couldn't find anything.Analyzer couldn't find any suitable barcode from the provided image. Try changing scanType to proper HmsScanTypes.
decodeMultiAsyncOnFailureHmsScanError14Multi Async - On FailureAnalyzer failed to respond. Try recalling the API.
decodeMultiSyncCouldntFindHmsScanError15Multi Sync - Couldn't find anything.Analyzer couldn't find any suitable barcode from the provided image. Try changing scanType to proper HmsScanTypes.
mpCameraScanModeErrorHmsScanError16Please check your scan mode.Provided scan mode is not suitable for analyzer. Try to use HmsMultiProcessor's Constant Values.
decodeWithBitmapErrorHmsScanError17Please check your barcode and scan type.Analyzer couldn't find any suitable barcode from the provided image. Try changing scanType to proper HmsScanTypes.
buildBitmapHmsScanError18Barcode generation failed.Try changing barcode content according to your error logs.
hmsScanAnalyzerErrorHmsScanError19Analyzer is not available.Try recalling the API.
remoteViewErrorHmsScanError20Remote View is not initialized.Try recalling the API.
mpChannelErrorHmsScanError21Multi Processor Channel cannot be initialized.Try recalling the API.

HmsScanForm

ConstantTypeValueDescription
OtherFormint-1Unknown barcode content.
ContactDetailFormint1009Contact information.
EmailContentFormint1002Email information.
ISBNNumberFormint1012ISBN.
TelPhoneNumberFormint1003Phone number.
ArticleNumberFormint1001Product information.
SmsFormint1005SMS content.
PureTextFormint1004Text.
UrlFormint1006URL.
WIFIConnectInfoFormint1007Wi-Fi.
LocationCoordinateFormint1011Location.
EventInfoFormint1008Calender event.
DriverInfoFormint1010Driver license information.

HmsScanTypes

ConstantTypeValueDescription
OtherScanTypeint-1Unknown barcode format.
AllScanTypeint0All supported barcode formats.
Code128int64Code 128.
Code39int16Code 39.
Code93int32Code 93.
Codabarint4096Codabar.
DataMatrixint4Data Matrix.
EAN13int128EAN-13.
EAN8int256EAN-8.
ITF14int512ITF-14.
QRCodeint1QR code.
UPCCodeAint1024UPC-A.
UPCCodeEint2048UPC-E.
Pdf417int8PDF-417.
Aztecint2Aztec barcode.

You can read more and get detailed information about the interfaces described above from developer.huawei.com.

Configuration Description

Preparing for Release

Before building a release version of your app you may need to customize the proguard-rules.pro obfuscation configuration file to prevent the HMS Core SDK from being obfuscated. Add the configurations below to exclude the HMS Core SDK from obfuscation. For more information on this topic refer to this Android developer guide.

<flutter_project>/android/app/proguard-rules. pro

-ignorewarnings
-keepattributes *Annotation*
-keepattributes Exceptions
-keepattributes InnerClasses
-keepattributes Signature
-keepattributes SourceFile,LineNumberTable
-keep class com.hianalytics.android.**{*;}
-keep class com.huawei.updatesdk.**{*;}
-keep class com.huawei.hms.**{*;}

<flutter_project>/android/app/build.gradle

buildTypes {
    debug {
        signingConfig signingConfigs.config
    }
    release {
        signingConfig signingConfigs.config
        // Enables code shrinking, obfuscation and optimization for release builds
        minifyEnabled true
        // Unused resources will be removed, resources defined in the res/raw/keep.xml will be kept.
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

Sample Project

This plugin includes a demo project in the example folder, there you can find more usage examples.

Questions or Issues

If you have questions about how to use HMS samples, try the following options:

  • Stack Overflow is the best place for any programming questions. Be sure to tag your question with huawei-mobile-services.
  • Github is the official repository for these plugins, You can open an issue or submit your ideas.
  • Huawei Developer Forum HMS Core Module is great for general questions, or seeking recommendations and opinions.
  • Huawei Developer Docs is place to official documentation for all HMS Core Kits, you can find detailed documentations in there.

If you run into a bug in our samples, please submit an issue to the Github Repository.

Licensing and Terms

Huawei Scan Flutter Plugin uses the Apache 2.0 license.

Libraries

AddressInfo
BorderRect
BuildBitmapRequest
ContactDetail
CornerPoint
CustomizedViewRequest
DecodeRequest
DefaultViewRequest
DriverInfo
EmailContent
EventInfo
EventTime
HmsCustomizedView
HmsMultiProcessor
HmsScan
HmsScanErrors
HmsScanForm
HmsScanPermissions
HmsScanTypes
HmsScanUtils
LinkUrl
LocationCoordinate
MultiCameraRequest
PeopleName
ScanResponse
ScanResponseList
ScanTextOptions
SmsContent
TelPhoneNumber
WiFiConnectionInfo
hms_scan_library