Search code examples
androidflutterbarcodebarcode-scanner

How to use barcode_scan widget as a child to some other widget?


I am using barcode_scan widget in my flutter app when I call Scan method this widget takes up the whole screen where it show the camera, I want to show that camera view inside another widget.


Solution

  • You can use package https://pub.dev/packages/last_qr_scanner or https://pub.dev/packages/qr_code_scanner
    They both use platform view within Flutter

    enter image description here

    full example code of last_qr_scanner

    import 'package:flutter/material.dart';
    
    import 'package:flutter/services.dart';
    import 'package:last_qr_scanner/last_qr_scanner.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatefulWidget {
      const MyApp({
        Key key,
      }) : super(key: key);
      @override
      _MyAppState createState() => _MyAppState();
    }
    
    class _MyAppState extends State<MyApp> {
      final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');
      var qrText = ""; 
      var controller;
    
      @override
      void initState() {
        super.initState();
      }
    
      void _onQRViewCreated(QRViewController controller) {
        this.controller = controller;
        final channel = controller.channel;
        controller.init(qrKey);
        channel.setMethodCallHandler((MethodCall call) async {
          switch (call.method) {
            case "onRecognizeQR":
              dynamic arguments = call.arguments;
              setState(() {
                qrText = arguments.toString();
              });
          }
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return new MaterialApp(
          home: new Scaffold(
            appBar: new AppBar(
              title: new Text('Barcode Scanner Example'),
            ),
            body: Column(
              children: <Widget>[
                Expanded(
                  child: LastQrScannerPreview(
                    key: qrKey,
                    onQRViewCreated: _onQRViewCreated,
                  ),
                  flex: 4,
                ),
                Expanded(
                  child: Text("This is the result of scan: $qrText"),
                  flex: 1,
                ),
                Expanded(
                  child: RaisedButton(
                    onPressed: () {
                      this.controller.toggleTorch();                  
                    },
                    child: Text("Toggle Torch"),
                  ),
                  flex: 1,
                )
              ],
            ),
          ),
        );
      }
    }