Made the grid size adjustable (default is 12x12)
parent
cfb929afac
commit
c3dbf3034e
|
@ -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<MyHomePage> createState() => _MyHomePageState();
|
||||
}
|
||||
|
||||
class _MyHomePageState extends State<MyHomePage> {
|
||||
List<List<int>> _grid = List.generate(5, (_) => List.generate(5, (_) => Random().nextInt(5)));
|
||||
late List<List<int>> _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<MyHomePage> {
|
|||
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),
|
||||
|
|
Loading…
Reference in New Issue