Flutter – How to use Barcode Scanner

August 9, 2023

This article aims to provide you with instructions on how to utilize the simple_barcode_scanner package to scan barcodes within a Flutter application.

For context, I’m utilizing version 0.0.8 of simple_barcode_scanner alongside Flutter version 3.10.6.

Follow these steps to integrate the package:

1. Open your pubspec.yaml file and include the following package within the dependencies section:

simple_barcode_scanner: ^0.0.8

2. Within your Dart file, import the simple_barcode_scanner package:

import 'package:simple_barcode_scanner/simple_barcode_scanner.dart';

3. Declare a variable to store barcode string (make sure to add outside of build widget), and a button that calls Barcode Scanner.

String _barcode = '';

ElevatedButton(
   onPressed: () async {
      var res = await Navigator.push(
         context,
         MaterialPageRoute(
            builder: (context) =>
               const SimpleBarcodeScannerPage(
                  appBarTitle: 'Scan a package',
               ),
            fullscreenDialog: true,
         ),
      );
      setState(() {
         if (res is String) {
            _barcode = res;
         }
      });
   },
   child: Text('Scan a barcode'),
),

By following these steps, you’ll be able to successfully incorporate barcode scanning functionality into your Flutter application using the simple_barcode_scanner package.