Search code examples
flutterqr-code

QRCode Generator


In my flutter application I wanted to generate QR code that have the current time and user ID as data.Whenever I click on the button new QR code should be generated based on the time. This is my code for my qr

QrImage(
   data: tdata + userId,
   size: 250,
),

this is the code for my button

Button(
  onPressed: () {
  },
  label: const Text(
    'Generate',
  ),
),

Solution

  • I have used this package https://pub.dev/packages/qr_flutter

    This is the demo of what you are looking for .

    
    import 'package:qr_flutter/qr_flutter.dart';
    
    import 'package:flutter/material.dart';
    
    void main() => runApp(const MyApp());
    
    class MyApp extends StatelessWidget {
      const MyApp({Key? key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return const MaterialApp(home: QRGenerator());
      }
    }
    
    class QRGenerator extends StatefulWidget {
      const QRGenerator({Key? key}) : super(key: key);
    
      @override
      State<QRGenerator> createState() => _QRGeneratorState();
    }
    
    class _QRGeneratorState extends State<QRGenerator> {
      String userId = "userIdHere";
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                QrImage(
                  data: "$userId ${DateTime.now()}",
                  version: QrVersions.auto,
                  size: 200.0,
                ),
                const SizedBox(
                  height: 20,
                ),
                MaterialButton(
                  onPressed: () {
                    setState(() {});
                  },
                  child: const Text("Generate QR Code"),
                  color: Colors.blue,
                )
              ],
            ),
          ),
        );
      }
    }
    
    

    Set the state when the button is clicked.. it will fetch the current time and add the user id to it and generate a new QR code.

    preview

    Edit Create an int

    int maxAttempt = 10;
    

    On each button tap decrease this value

    maxAttempt--;
    setState((){});
    

    Now on button click setState only if maxAttempt > 0 or you can also add condition in widget

    (maxAttempt> 0) ? QrImage(): Text("max attempts reached")