Flutter QR Code Generator with Share Functionality

This Flutter code demonstrates how to create a simple QR code generator and share the generated QR code as an image using the share_plus package. The code generates a QR code from a URL provided as a parameter and displays it on the screen. 

When the user taps the share button, the generated QR code is saved as an image file and shared using the share_plus package and path_provider  for getting commonly used locations on host platform file systems, such as the temp and app data directories.


Usage:

Flutter plugin for sharing content via the platform share UI, using the ACTION_SEND intent on Android and UIActivityViewController on iOS.


Code:

import 'package:flutter/material.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:share_plus/share_plus.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';

class QRGeneratorShare extends StatefulWidget {
  final String url;

  QRGeneratorShare({super.key, required this.url});

  @override
  _QRGeneratorShareState createState() => _QRGeneratorShareState();
}

class _QRGeneratorShareState extends State {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter QR'),
      ),
      body: Center(
        child: QrImage(
          data: widget.url, // Generate QR code from the URL provided as a parameter
          version: QrVersions.auto,
          size: 200.0,
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => _shareQRImage(),
        child: Icon(Icons.share),
      ),
    );
  }

  Future _shareQRImage() async {
    final image = await QrPainter(
      data: widget.url,
      version: QrVersions.auto,
      gapless: false,
      color: Colors.black,
      emptyColor: Colors.white,
    ).toImageData(200.0); // Generate QR code image data

    final filename = 'qr_code.png'; 
    final tempDir = await getTemporaryDirectory(); // Get temporary directory to store the generated image
    final file = await File('${tempDir.path}/$filename').create(); // Create a file to store the generated image
    var bytes = image!.buffer.asUint8List(); // Get the image bytes
    await file.writeAsBytes(bytes); // Write the image bytes to the file
    final path = await Share.shareFiles([file.path], text: 'QR code for ${widget.url}', subject: 'QR Code', mimeTypes: ['image/png']); // Share the generated image using the share_plus package
    //print('QR code shared to: $path');
  }
}


..


Properties:

  • url: The URL used to generate the QR code. It is a required parameter.
  • image: The generated QR code image data.
  • filename: The name of the file to store the generated image.
  • tempDir: The temporary directory used to store the generated image.
  • file: The file used to store the generated image.
..
Flutter Plugins,

..

GET source code on Github:

Comments