When & why is it a good idea to call findRenderObject?

792 views
Skip to first unread message

MrLarryQ

unread,
Mar 19, 2019, 6:30:39 PM3/19/19
to Flutter Dev
I'm looking at some code someone has written, and had a question about GlobalKeys and the findRenderObject method.   Here's the class in question:

class QrCodeImage extends StatelessWidget {

final String product;
GlobalKey _repaintQrImage = GlobalKey();

QrCodeImage({Key key, this.product}) : super(key: key);

Future<File> _captureByteData() async {
RenderRepaintBoundary boundary = _repaintQrImage.currentContext.findRenderObject();
ui.Image image = await boundary.toImage(
pixelRatio: 3.0,
);
var byteData = await image.toByteData(
format: ui.ImageByteFormat.png,
);
File imageFile = File(await FireStorage.getFilePath());
return await FireStorage.writeQrImage(imageFile, byteData);
}

@override
Widget build(BuildContext context) {
if(product != null)
return Expanded(
child: Padding(
padding: const EdgeInsets.only(
top: 60,
),
child: RepaintBoundary(
key: _repaintQrImage,
child: GestureDetector(
onTap: () {
_captureByteData().then((imageFile) {
FirebaseQrDetector(imageFile).detectQrCode();
});
},
child: QrImage(
backgroundColor: Colors.white,
padding: EdgeInsets.all(40.0),
data: product,
size: 300,
),
),
),
),
);
else
return Container();
}
}



Basically what's happening is we capture an image from the screen and then manipulate it.   That part isn't germane to my question however; I'm more interested in the use of GlobalKey() and the findRenderObject() method. 

I've read up about global keys and my limited understanding is they give you a 'unique value' and so a quick way to identify a widget.  However I'm not entirely sure why we're using a global key in this instance since a key is supposedly passed into the class's constructor?

That's one point, probably a minor one that I'm not quite getting.  The larger one is why we create a RepaintBoundary widget and what the point of findRenderObject is.  The author of the class, when explaining it in a lecture, vaguely referred to 'performance benefits' when he mentioned the code in question but never elaborated.  I was hoping someone could provide a better explanation of what's going on and when I would want to do this in my own code.















Reply all
Reply to author
Forward
0 new messages