Last active
January 12, 2023 14:54
-
-
Save creativecreatorormaybenot/a984d3a64f9ce5362cd31fe6bb585d43 to your computer and use it in GitHub Desktop.
Drawing beyond Widgets' borders (https://stackoverflow.com/a/57159918/6509751)
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
import 'package:flutter/material.dart'; | |
main() { | |
runApp(MaterialApp( | |
home: Scaffold( | |
body: SafeArea( | |
child: Stack( | |
children: <Widget>[ | |
const Lines(), | |
const IgnorePointer( | |
child: Boxes(), | |
), | |
], | |
), | |
), | |
), | |
)); | |
} | |
class Boxes extends StatelessWidget { | |
const Boxes({Key key}) : super(key: key); | |
@override | |
build(_) => GridView.count( | |
crossAxisCount: 2, | |
mainAxisSpacing: 25, | |
crossAxisSpacing: 25, | |
padding: const EdgeInsets.all(25), | |
children: <Widget>[ | |
for (int i = 0; i < 6; i++) | |
Container( | |
color: const Color(0xffe4f2fd), | |
foregroundDecoration: BoxDecoration( | |
border: Border.all( | |
color: const Color(0xffc2d2e1), | |
width: 2, | |
)), | |
child: const Center( | |
child: Text('MyBox'), | |
), | |
) | |
], | |
); | |
} | |
class Lines extends StatefulWidget { | |
const Lines({Key key}) : super(key: key); | |
@override | |
createState() => _LinesState(); | |
} | |
class _LinesState extends State<Lines> { | |
Offset start; | |
Offset end; | |
@override | |
build(_) => GestureDetector( | |
onTap: () => print('t'), | |
onPanStart: (details) { | |
print(details.localPosition); | |
setState(() { | |
start = details.localPosition; | |
end = null; | |
}); | |
}, | |
onPanUpdate: (details) { | |
setState(() { | |
end = details.localPosition; | |
}); | |
}, | |
child: CustomPaint( | |
size: Size.infinite, | |
painter: LinesPainter(start, end), | |
), | |
); | |
} | |
class LinesPainter extends CustomPainter { | |
final Offset start, end; | |
LinesPainter(this.start, this.end); | |
@override | |
void paint(Canvas canvas, Size size) { | |
if (start == null || end == null) return; | |
canvas.drawLine( | |
start, | |
end, | |
Paint() | |
..strokeWidth = 4 | |
..color = Colors.redAccent); | |
} | |
@override | |
bool shouldRepaint(LinesPainter oldDelegate) { | |
return oldDelegate.start != start || oldDelegate.end != end; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment