From c3dbf3034e2d520dad373fcd3ff78d0a4cf6ac5e Mon Sep 17 00:00:00 2001 From: Lachfrosch Date: Wed, 8 May 2024 16:05:52 +0200 Subject: [PATCH] Made the grid size adjustable (default is 12x12) --- lib/main.dart | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/lib/main.dart b/lib/main.dart index d0132d0..fda1406 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -7,6 +7,7 @@ void main() { class MyApp extends StatelessWidget { const MyApp({super.key}); + final int gridSize = 12; // This widget is the root of your application. @override @@ -32,13 +33,13 @@ class MyApp extends StatelessWidget { colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), useMaterial3: true, ), - home: const MyHomePage(title: 'Flutter Demo Home Page'), + home: const MyHomePage(title: 'Flutter Demo Home Page', gridSize: 12), ); } } class MyHomePage extends StatefulWidget { - const MyHomePage({super.key, required this.title}); + const MyHomePage({super.key, required this.title, required this.gridSize}); // This widget is the home page of your application. It is stateful, meaning // that it has a State object (defined below) that contains fields that affect @@ -50,15 +51,25 @@ class MyHomePage extends StatefulWidget { // always marked "final". final String title; + final int gridSize; @override State createState() => _MyHomePageState(); } class _MyHomePageState extends State { - List> _grid = List.generate(5, (_) => List.generate(5, (_) => Random().nextInt(5))); + late List> _grid; @override + void initState() { + super.initState(); + _initializeGrid(); + } + + void _initializeGrid() { + _grid = List.generate(widget.gridSize, (_) => List.generate(widget.gridSize, (_) => Random().nextInt(5))); + } + Widget build(BuildContext context) { return Scaffold( appBar: AppBar( @@ -68,16 +79,16 @@ class _MyHomePageState extends State { child: GridView.builder( shrinkWrap: true, gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( - crossAxisCount: 5, + crossAxisCount: widget.gridSize, ), - itemCount: _grid.length * _grid.length, + itemCount: widget.gridSize * widget.gridSize, itemBuilder: (BuildContext context, int index) { - int row = index ~/ _grid.length; - int col = index % _grid.length; + int row = index ~/ widget.gridSize; + int col = index % widget.gridSize; return GestureDetector( onTap: () => _onTileTap(row, col), child: Container( - margin: EdgeInsets.all(4), + margin: EdgeInsets.all(2), decoration: BoxDecoration( color: _getColor(_grid[row][col]), borderRadius: BorderRadius.circular(8),