If you want to draw on a CustomPaint widget at position of the pointer down event? You don’t necessarily have to wrap the listener in a widget. You can also use a GlobalKey to get the RenderObject.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | import 'package:flutter/material.dart'; void main() { runApp(new MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( home: new MyHomePage(), ); } } class MyHomePage extends StatefulWidget { @override State createState() => new MyHomePageState(); } class MyHomePageState extends State<MyHomePage> { GlobalKey _paintKey = new GlobalKey(); Offset _offset; @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text('CustomPaint example'), ), body: new Listener( onPointerDown: (PointerDownEvent event) { RenderBox referenceBox = _paintKey.currentContext.findRenderObject(); Offset offset = referenceBox.globalToLocal(event.position); setState(() { _offset = offset; }); }, child: new CustomPaint( key: _paintKey, painter: new MyCustomPainter(_offset), child: new ConstrainedBox( constraints: new BoxConstraints.expand(), ), ), ), ); } } class MyCustomPainter extends CustomPainter { final Offset _offset; MyCustomPainter(this._offset); @override void paint(Canvas canvas, Size size) { if (_offset == null) return; canvas.drawCircle(_offset, 10.0, new Paint()..color = Colors.blue); } @override bool shouldRepaint(MyCustomPainter other) => other._offset != _offset; } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.