Search code examples
androidflutterqr-codedart-null-safety

Null check operator used on a null value. For saving qr image


Im getting null check error when capturing the qr image. it returns null check operator used on a null value. This is what i got. i would like it to save files to the local storage

 String _dataList() { 
    String encodedJson = jsonEncode(data);
    print(encodedJson);
    return encodedJson;
  }
Future<void> _captureAndSharePng() async {
    try {
      RenderRepaintBoundary boundary = globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
      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 File('${tempDir.path}/image.png').create();
      await file.writeAsBytes(pngBytes!);

      await Share.shareXFiles([XFile('assets/images/qrCode.png')], text: _dataList());
    } catch (e) {
      print(e.toString());
    }
  }

RepaintBoundary(
                                key: qrKey,
                                child: QrImage(
                                  padding: const EdgeInsets.all(11),
                                  data: _dataList(),
                                  backgroundColor: Colors.white,
                                  size: height*0.2,
                                  errorCorrectionLevel: QrErrorCorrectLevel.L,
                                  dataModuleStyle: const QrDataModuleStyle(dataModuleShape: QrDataModuleShape.circle, color: Colors.black),
                                ),
                              ),

Solution

  • This issue can be happened from two place, you may miss the using globalKey. Try checking null before using !.

    Future<void> _captureAndSharePng() async {
        try {
          RenderRepaintBoundary? boundary = globalKey.currentContext?.findRenderObject() as RenderRepaintBoundary?;
          if(boundary ==null){ 
             debugPrint("got null boundary");
             return;
           }
          var image = await boundary.toImage();
          ByteData? byteData = await image.toByteData(format: ImageByteFormat.png);
          Uint8List? pngBytes = byteData?.buffer.asUint8List();
          
          if(pngBytes==null){
           debugPrint("got null pngBytes");
             return;
           }
    
        ....