How to Build QR Code Generator, Scanner, and Sharing App in Flutter

In this article, we will build a Flutter application with the features of scanning QR Code using Camera, generating QR Code with text data, and sharing the image file of QR code to other apps using platform specific image sharing mechanism for both iOS and Android.

What our application consists of:

  • Home Screen Widget for user to select scan QR Code or generate QR Code.
  • QR Code Scanner Widget for user to scan QR code with device camera and view the text result of the QR code.
  • QR Code Generator Widget for user to enter text data and generate QR Code Widget, convert widget to image file, and share image file to other application.

Project Dependencies

Our project pubspec.yaml file plugin dependencies consists of:

dependencies:   
  ....
  path_provider: 0.4.1
  barcode_scan: ^0.0.4
  qr_flutter: ^1.1.1
  • path_provider by Flutter Team. A Flutter plugin for finding commonly used locations on the filesystem. Supports iOS and Android.
  • barcode_scan by Matthew. A Flutter plugin for scanning 2D barcodes and QR codes as a wrapper using specific iOS mikebuss/MTBBarcodeScanner and Android dm77/barcodescanner library.
  • qr_flutter by Luke Freeman. QR.Flutter is a QR code generation and rendering library for Flutter.

Home Screen Widget

Our app home screen widget allow the user to select whether to perform scan or generate QR Code by tapping on button. The build widget return a Column with 2 RaisedButton as the children, one for routing to generating QR code screen and one for routing to scanning QR code screen when the button is tapped.

import 'package:flutter/material.dart';
import 'package:qr_scanner_generator/scan.dart';
import 'package:qr_scanner_generator/generate.dart';
import 'package:flutter/rendering.dart';

class HomeScreen extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: Text('QR Code Scanner & Generator'),
        ),
        body: Center(
            child:
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: <Widget>[
                  Padding(
                      padding: EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
                      child: RaisedButton(
                          color: Colors.blue,
                          textColor: Colors.white,
                          splashColor: Colors.blueGrey,
                          onPressed: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(builder: (context) => Scan()),
                            );
                          },
                          child: const Text('SCAN QR CODE')
                      ),
                    ),
                   Padding(
                      padding: EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
                      child: RaisedButton(
                          color: Colors.blue,
                          textColor: Colors.white,
                          splashColor: Colors.blueGrey,
                          onPressed: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(builder: (context) => GenerateScreen()),
                            );
                          },
                          child: const Text('GENERATE QR CODE')
                      ),
                    ),
                ],
              )
          ),
        );
  }
}

Scan Screen QR Code Widget

The scan screen widget display the start scan with camera button and a
Text widget that display the result of the camera QR code scan. It uses the Column Widget as the parent for the Text and Button children.

When user taps on Button, the async scan function is invoked. It will use the BarcodeScanner class from the barcode_scanner plugin dependencies to start the camera viewfinder both on iOS and Android for user to point and scan the QR Code.

If QR code is found, the result of the text will be returned and will be assigned to the barcode instance variable inside the setState function that will trigger widget render. The barcode instance variable will be assigned to Text Widget to display the result of the QR Code scan. If Error occurs, we just set the barcode property with the error message.

import 'dart:async';

import 'package:barcode_scan/barcode_scan.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class ScanScreen extends StatefulWidget {
  @override
  _ScanState createState() => new _ScanState();
}

class _ScanState extends State<ScanScreen> {
  String barcode = "";

  @override
  initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: new AppBar(
          title: new Text('QR Code Scanner'),
        ),
        body: new Center(
          child: new Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
                child: RaisedButton(
                    color: Colors.blue,
                    textColor: Colors.white,
                    splashColor: Colors.blueGrey,
                    onPressed: scan,
                    child: const Text('START CAMERA SCAN')
                ),
              )
              ,
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
                child: Text(barcode, textAlign: TextAlign.center,),
              )
              ,
            ],
          ),
        ));
  }

  Future scan() async {
    try {
      String barcode = await BarcodeScanner.scan();
      setState(() => this.barcode = barcode);
    } on PlatformException catch (e) {
      if (e.code == BarcodeScanner.CameraAccessDenied) {
        setState(() {
          this.barcode = 'The user did not grant the camera permission!';
        });
      } else {
        setState(() => this.barcode = 'Unknown error: $e');
      }
    } on FormatException{
      setState(() => this.barcode = 'null (User returned using the "back"-button before scanning anything. Result)');
    } catch (e) {
      setState(() => this.barcode = 'Unknown error: $e');
    }
  }
}

Generate Screen QR Code Widget

The Generate screen widget displays a TextField for user enter the text data that will be used to generate the QR Code widget using the qr_flutter plugin when the user tap on the submit Button. It also provides a Share Button in the Navigation bar to share the image png file to other apps in iOS and Android.

When user has filled the TextField and tap on the submit button, we assign the _dataString property value inside the setState method that will trigger widget render. Our Widget will pass the _dataString property to the QrImage widget that will process the text and render the qr using custom qr painter. We wrap the QrImage inside the RepaintBoundary widget with a GlobalKey property so we can get the RenderRepaintBoundary later with the key and use the built in Flutter to Image method on the RenderRepaintBoundary widget that will convert the widget to a png file.

import 'package:flutter/material.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:flutter/services.dart';
import 'dart:async';
import 'dart:typed_data';
import 'dart:ui';
import 'dart:io';
import 'package:flutter/rendering.dart';
import 'package:path_provider/path_provider.dart';

class GenerateScreen extends StatefulWidget {

  @override
  State<StatefulWidget> createState() => GenerateScreenState();
}

class GenerateScreenState extends State<GenerateScreen> {

  static const double _topSectionTopPadding = 50.0;
  static const double _topSectionBottomPadding = 20.0;
  static const double _topSectionHeight = 50.0;

  GlobalKey globalKey = new GlobalKey();
  String _dataString = "Hello from this QR";
  String _inputErrorText;
  final TextEditingController _textController =  TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('QR Code Generator'),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.share),
            onPressed: _captureAndSharePng,
          )
        ],
      ),
      body: _contentWidget(),
    );
  }

  Future<void> _captureAndSharePng() async {
    try {
      RenderRepaintBoundary boundary = globalKey.currentContext.findRenderObject();
      var image = await boundary.toImage();
      ByteData byteData = await image.toByteData(format: ImageByteFormat.png);
      Uint8List pngBytes = byteData.buffer.asUint8List();

      final tempDir = await getTemporaryDirectory();
      final file = await new File('${tempDir.path}/image.png').create();
      await file.writeAsBytes(pngBytes);

      final channel = const MethodChannel('channel:me.alfian.share/share');
      channel.invokeMethod('shareFile', 'image.png');

    } catch(e) {
      print(e.toString());
    }
  }

  _contentWidget() {
    final bodyHeight = MediaQuery.of(context).size.height - MediaQuery.of(context).viewInsets.bottom;
    return  Container(
      color: const Color(0xFFFFFFFF),
      child:  Column(
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.only(
              top: _topSectionTopPadding,
              left: 20.0,
              right: 10.0,
              bottom: _topSectionBottomPadding,
            ),
            child:  Container(
              height: _topSectionHeight,
              child:  Row(
                mainAxisSize: MainAxisSize.max,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: <Widget>[
                  Expanded(
                    child:  TextField(
                      controller: _textController,
                      decoration:  InputDecoration(
                        hintText: "Enter a custom message",
                        errorText: _inputErrorText,
                      ),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(left: 10.0),
                    child:  FlatButton(
                      child:  Text("SUBMIT"),
                      onPressed: () {
                        setState((){
                          _dataString = _textController.text;
                          _inputErrorText = null;
                        });
                      },
                    ),
                  )
                ],
              ),
            ),
          ),
          Expanded(
            child:  Center(
              child: RepaintBoundary(
                key: globalKey,
                child: QrImage(
                  data: _dataString,
                  size: 0.5 * bodyHeight,
                  onError: (ex) {
                    print("[QR] ERROR - $ex");
                    setState((){
                      _inputErrorText = "Error! Maybe your input value is too long?";
                    });
                  },
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

Generate QR Code PNG Image and Sharing with Platform Specific Channel

When user taps on the sharing button we invoke the _captureAndSharePng function that will get the RepaintBoundary object with GlobalKey passed to RepaintBoundary widget. Then we call the toImage method that will convert the widget to Image object and convert the Image object using toByteData with png format.

After that we get the bytes data, get the application temporary directory and save the data inside the temporary directory. To share the image, we will use platform specific channel API method that will pass the image path and call shareImage on each platform for iOS and Android.

We need to add our shareImage function on each platform project, you can refer to this stack overflow post on how to integrate on both iOS and Android. https://stackoverflow.com/questions/44181343/how-do-i-share-an-image-on-ios-and-android-using-flutter.

On iOS the UIActivityViewController will be used and on Android it will use Intent.ACTION_SEND to send the image file, both will get the file from the temporary directory using the image path passed.

Future<void> _captureAndSharePng() async { 
   try {    
      RenderRepaintBoundary boundary = globalKey.currentContext.findRenderObject(); 
      var image = await boundary.toImage();
      ByteData byteData = await image.toByteData(format: ImageByteFormat.png);
      Uint8List pngBytes = byteData.buffer.asUint8List();       final tempDir = await getTemporaryDirectory();
      final file = await new File('${tempDir.path}/image.png').create();
      await file.writeAsBytes(pngBytes);
       final channel = const MethodChannel('channel:me.alfian.share/share');
      channel.invokeMethod('shareFile', 'image.png');
     } catch(e) {
      print(e.toString());
   }
}

Conclusion

It’s a wrap. We have built the Flutter App with the abilities to scan, generate, and share QR code that works both on iOS and Android. Flutter Platform Specific Channel API makes it easy for us to use native libraries such as QR code scanner, image sharing, and communicate back the result to the Flutter App.

The project source code is available on GitHub repository.

Happy Fluttering and stay tuned!.

#flutter #dart #mobile-apps

What is GEEK

Buddha Community

How to Build QR Code Generator, Scanner, and Sharing App in Flutter

Google's Flutter 1.20 stable announced with new features - Navoki

Flutter Google cross-platform UI framework has released a new version 1.20 stable.

Flutter is Google’s UI framework to make apps for Android, iOS, Web, Windows, Mac, Linux, and Fuchsia OS. Since the last 2 years, the flutter Framework has already achieved popularity among mobile developers to develop Android and iOS apps. In the last few releases, Flutter also added the support of making web applications and desktop applications.

Last month they introduced the support of the Linux desktop app that can be distributed through Canonical Snap Store(Snapcraft), this enables the developers to publish there Linux desktop app for their users and publish on Snap Store.  If you want to learn how to Publish Flutter Desktop app in Snap Store that here is the tutorial.

Flutter 1.20 Framework is built on Google’s made Dart programming language that is a cross-platform language providing native performance, new UI widgets, and other more features for the developer usage.

Here are the few key points of this release:

Performance improvements for Flutter and Dart

In this release, they have got multiple performance improvements in the Dart language itself. A new improvement is to reduce the app size in the release versions of the app. Another performance improvement is to reduce junk in the display of app animation by using the warm-up phase.

sksl_warm-up

If your app is junk information during the first run then the Skia Shading Language shader provides for pre-compilation as part of your app’s build. This can speed it up by more than 2x.

Added a better support of mouse cursors for web and desktop flutter app,. Now many widgets will show cursor on top of them or you can specify the type of supported cursor you want.

Autofill for mobile text fields

Autofill was already supported in native applications now its been added to the Flutter SDK. Now prefilled information stored by your OS can be used for autofill in the application. This feature will be available soon on the flutter web.

flutter_autofill

A new widget for interaction

InteractiveViewer is a new widget design for common interactions in your app like pan, zoom drag and drop for resizing the widget. Informations on this you can check more on this API documentation where you can try this widget on the DartPad. In this release, drag-drop has more features added like you can know precisely where the drop happened and get the position.

Updated Material Slider, RangeSlider, TimePicker, and DatePicker

In this new release, there are many pre-existing widgets that were updated to match the latest material guidelines, these updates include better interaction with Slider and RangeSliderDatePicker with support for date range and time picker with the new style.

flutter_DatePicker

New pubspec.yaml format

Other than these widget updates there is some update within the project also like in pubspec.yaml file format. If you are a flutter plugin publisher then your old pubspec.yaml  is no longer supported to publish a plugin as the older format does not specify for which platform plugin you are making. All existing plugin will continue to work with flutter apps but you should make a plugin update as soon as possible.

Preview of embedded Dart DevTools in Visual Studio Code

Visual Studio code flutter extension got an update in this release. You get a preview of new features where you can analyze that Dev tools in your coding workspace. Enable this feature in your vs code by _dart.previewEmbeddedDevTools_setting. Dart DevTools menu you can choose your favorite page embed on your code workspace.

Network tracking

The updated the Dev tools comes with the network page that enables network profiling. You can track the timings and other information like status and content type of your** network calls** within your app. You can also monitor gRPC traffic.

Generate type-safe platform channels for platform interop

Pigeon is a command-line tool that will generate types of safe platform channels without adding additional dependencies. With this instead of manually matching method strings on platform channel and serializing arguments, you can invoke native class and pass nonprimitive data objects by directly calling the Dartmethod.

There is still a long list of updates in the new version of Flutter 1.2 that we cannot cover in this blog. You can get more details you can visit the official site to know more. Also, you can subscribe to the Navoki newsletter to get updates on these features and upcoming new updates and lessons. In upcoming new versions, we might see more new features and improvements.

You can get more free Flutter tutorials you can follow these courses:

#dart #developers #flutter #app developed #dart devtools in visual studio code #firebase local emulator suite in flutter #flutter autofill #flutter date picker #flutter desktop linux app build and publish on snapcraft store #flutter pigeon #flutter range slider #flutter slider #flutter time picker #flutter tutorial #flutter widget #google flutter #linux #navoki #pubspec format #setup flutter desktop on windows

Hire Dedicated Flutter App Developer USA| Flutter App Developers

Hire Flutter App Developers: WebClues Infotech is a Flutter App Development company. Our Flutter mobile app development team can create cross-platform apps for different industry verticals. Our Flutter developers will help you extend your business’s scope by developing enhanced functionality and a feature-rich app. To provide a rich user experience to your users, hire dedicated Flutter app developers from WebClues Infotech today!

#hire flutter app developers #hire dedicated flutter app developer usa #hire flutter app developer usa #hire dedicated flutter app developer #hire flutter developer #flutter app development company

Best Flutter App Development Company

Are you looking for the best flutter app development company? Then AppClues Infotech is the leading flutter app development company in USA offering the best service worldwide. We focused on developing hybrid mobile apps on Android & iOS and assures our end-user about exceptional and functionally-rich mobile apps.

For more info:
Website: https://www.appcluesinfotech.com/
Email: info@appcluesinfotech.com
Call: +1-978-309-9910

#top flutter app development company in usa #best flutter app development service #best flutter app development company #hire flutter app developers #flutter app development company #expert flutter app development company

Best Flutter App Development Company in USA & India

AppClues Infotech is one of the best flutter app development company in USA & India. Our diverse and experienced team of developers can help you sketch the smartest and quickest solution for your mobile app development projects with the most superior technology.

For more info:
Website: https://www.appcluesinfotech.com/
Email: info@appcluesinfotech.com
Call: +1-978-309-9910

#top flutter app development company in usa #best flutter app development service #best flutter app development company #hire flutter app developers #flutter app development company in usa & india #custom flutter app development service

Best Flutter App Development Services in USA

Looking for the best-in-class Flutter app development services in USA? We at AppClues Infotech offer next-generation mobile app development services using Google’s powerful framework, Flutter.

Our extremely trustworthy and exceptional Flutter app developers help enterprises and businesses to design high-quality native interfaces on cross-platform.

If you have any project ideas, hiring our Flutter app development services helps you get multi-platform applications with seamless animations, appealing UI, and excellent performance.

Flutter Mobile App Development Services
• Flutter Custom App Development
• Flutter App UI/UX Design
• Flutter Widget Development
• Flutter App QA Testing & Maintenance
• Flutter App Updations & Migration
• Flutter for Embedded Devices
• Flutter Development Consultation

For more info:
Website: https://www.appcluesinfotech.com/
Email: info@appcluesinfotech.com
Call: +1-978-309-9910

#top flutter app development company in usa #best flutter app development service in usa #best flutter app development company usa #hire flutter app developers in usa #best flutter app development services in usa #custom flutter app development services in usa