Last active
July 12, 2023 03:00
-
-
Save sma/c6a9111d58c3deb83711106cec6152ee to your computer and use it in GitHub Desktop.
A flutter example demonstrating a custom painter drawing selectable rects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// run in DartPad: <https://dartpad.dev/c6a9111d58c3deb83711106cec6152ee> | |
import 'package:flutter/material.dart'; | |
void main() { | |
runApp(MaterialApp(home: RectsExample())); | |
} | |
class RectsExample extends StatefulWidget { | |
@override | |
_RectsExampleState createState() => _RectsExampleState(); | |
} | |
class _RectsExampleState extends State<RectsExample> { | |
int _index = -1; | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
body: Center( | |
child: Rects( | |
rects: [ | |
Rect.fromLTRB(10, 20, 30, 40), | |
Rect.fromLTRB(40, 60, 80, 100), | |
], | |
selectedIndex: _index, | |
onSelected: (index) { | |
setState(() { | |
_index = index; | |
}); | |
}, | |
), | |
), | |
); | |
} | |
} | |
class Rects extends StatelessWidget { | |
final List<Rect> rects; | |
final void Function(int) onSelected; | |
final int selectedIndex; | |
const Rects({ | |
Key key, | |
@required this.rects, | |
@required this.onSelected, | |
this.selectedIndex = -1, | |
}) : super(key: key); | |
@override | |
Widget build(BuildContext context) { | |
return GestureDetector( | |
onTapDown: (details) { | |
RenderBox box = context.findRenderObject(); | |
final offset = box.globalToLocal(details.globalPosition); | |
final index = rects.lastIndexWhere((rect) => rect.contains(offset)); | |
if (index != -1) { | |
onSelected(index); | |
return; | |
} | |
onSelected(-1); | |
}, | |
child: CustomPaint( | |
size: Size(320, 240), | |
painter: _RectPainter(rects, selectedIndex), | |
), | |
); | |
} | |
} | |
class _RectPainter extends CustomPainter { | |
static Paint _red = Paint()..color = Colors.red; | |
static Paint _blue = Paint()..color = Colors.blue; | |
final List<Rect> rects; | |
final int selectedIndex; | |
_RectPainter(this.rects, this.selectedIndex); | |
@override | |
void paint(Canvas canvas, Size size) { | |
var i = 0; | |
for (Rect rect in rects) { | |
canvas.drawRect(rect, i++ == selectedIndex ? _red : _blue); | |
} | |
} | |
@override | |
bool shouldRepaint(CustomPainter oldDelegate) { | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@sma I need to do the same with a circle drawn with multiple arcs. I need to see which arc tapped by the user.
Please have a look at this. https://dartpad.dev/4f1dccf37910f61840d430a3947e4135. Please help me!