How to create signature area for mobile app in flutter?
You can create a signature area using GestureDetector
to record touches and CustomPaint
to draw on the screen. Here are a few tips:
RenderBox.globalToLocal
to convert the DragUpdateDetails
provided by GestureDetector.onPanUpdate
into relative coordinatesGestureDetector.onPanEnd
gesture handler to record the breaks between strokes.List
won’t automatically trigger a repaint because the CustomPainter
constructor arguments are the same. You can trigger a repaint by creating a new List
each time a new point is provided.Canvas.drawLine
to draw a rounded line between each of the recorded points of the signature.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 | import 'package:flutter/material.dart'; class SignaturePainter extends CustomPainter { SignaturePainter(this.points); final List<Offset> points; void paint(Canvas canvas, Size size) { Paint paint = new Paint() ..color = Colors.black ..strokeCap = StrokeCap.round ..strokeWidth = 5.0; for (int i = 0; i < points.length - 1; i++) { if (points[i] != null && points[i + 1] != null) canvas.drawLine(points[i], points[i + 1], paint); } } bool shouldRepaint(SignaturePainter other) => other.points != points; } class Signature extends StatefulWidget { SignatureState createState() => new SignatureState(); } class SignatureState extends State<Signature> { List<Offset> _points = <Offset>[]; Widget build(BuildContext context) { return new Stack( children: [ GestureDetector( onPanUpdate: (DragUpdateDetails details) { RenderBox referenceBox = context.findRenderObject(); Offset localPosition = referenceBox.globalToLocal(details.globalPosition); setState(() { _points = new List.from(_points)..add(localPosition); }); }, onPanEnd: (DragEndDetails details) => _points.add(null), ), CustomPaint(painter: SignaturePainter(_points), size: Size.infinite), ], ); } } class DemoApp extends StatelessWidget { Widget build(BuildContext context) => new Scaffold(body: new Signature()); } void main() => runApp(new MaterialApp(home: new DemoApp())); |
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.