Last active
November 21, 2023 01:20
-
-
Save kipsong133/ab14f5ca64811041f12ef592de9349be to your computer and use it in GitHub Desktop.
grid_paper_example.dart
This file contains 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'; | |
void main() { | |
runApp(const ExampleApp()); | |
} | |
class ExampleApp extends StatelessWidget { | |
const ExampleApp({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
home: GridPaper(), | |
); | |
} | |
} | |
class GridPaper extends StatelessWidget { | |
const GridPaper({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
backgroundColor: Colors.white, | |
body: Container( | |
color: Colors.white, | |
width: double.infinity, | |
height: double.infinity, | |
child: GridWidget(GridPainter()), | |
), | |
); | |
} | |
} | |
class GridWidget extends StatelessWidget { | |
final CustomPainter foreground; | |
const GridWidget(this.foreground, {Key? key}) : super(key: key); | |
@override | |
Widget build(BuildContext context) { | |
return Padding( | |
padding: const EdgeInsets.all(5), | |
child: SafeArea( | |
child: CustomPaint( | |
foregroundPainter: foreground, | |
painter: GridPainter(), | |
), | |
), | |
); | |
} | |
} | |
class GridPainter extends CustomPainter { | |
final double boxSize = 50; | |
@override | |
void paint(Canvas canvas, Size size) { | |
final vLines = (size.width ~/ boxSize) + 1; | |
final hLines = (size.height ~/ boxSize) + 1; | |
final paint = Paint() | |
..strokeWidth = 1 | |
..color = Colors.red | |
..style = PaintingStyle.stroke; | |
final path = Path(); | |
// Draw vertical lines | |
for (var i = 0; i < vLines; ++i) { | |
final x = boxSize * i; | |
path.moveTo(x, 0); | |
path.relativeLineTo(0, size.height); | |
} | |
// Draw horizontal lines | |
for (var i = 0; i < hLines; ++i) { | |
final y = boxSize * i; | |
path.moveTo(0, y); | |
path.relativeLineTo(size.width, 0); | |
} | |
canvas.drawPath(path, paint); | |
} | |
@override | |
bool shouldRepaint(covariant CustomPainter oldDelegate) { | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment