Как получить доступ к определенной ячейке в сгенерированном списке из количества просмотров сетки во Flutter?
Вот у меня список. Я хочу получить доступ к определенной позиции в этом списке в моем GridView.count.
Как у меня есть список, a = [133, 118, 117, 116, 115, 114];
Я хочу выяснить, что в моем List.generate, где я сгенерировал 225 ячеек, как мне получить доступ к ячейке, которая хранится в этом списке, a = [133, 118, 117, 116, 115, 114]; например, я хочу получить доступ к 4-му элементу (116) этого списка из этих 225 ячеек.
a = [133, 118, 117, 116, 115, 114];
child: GridView.count(
crossAxisCount: 15,
childAspectRatio: 1,
children: List<Widget>.generate(
225,
(index) {
return Stack(
children: [
GridTile(
child: Container(
decoration: BoxDecoration(
borderRadius:
BorderRadius.circular(5),
border:
Border.all(color: Colors.black),
),
),
),
],
);
},
),
),
1 ответ
Вот решение, передав индекс того, что вы хотите найти, и сопоставив его с индексом ячеек (согласно приведенному ниже коду):
import 'package:flutter/material.dart';
class GridExample extends StatefulWidget {
const GridExample({Key? key}) : super(key: key);
@override
_GridExampleState createState() => _GridExampleState();
}
class _GridExampleState extends State<GridExample> {
final a = [133, 118, 117, 116, 115, 114];
@override
Widget build(BuildContext context) {
return Container(
child: GridView.count(
crossAxisCount: 15,
childAspectRatio: 1,
children: List<Widget>.generate(
225,
(index) {
return Stack(
children: [
GridTile(
child: Tile(
index: index,
accessedCell: a[3],
),
),
],
);
},
),
),
);
}
}
class Tile extends StatefulWidget {
Tile({
required this.index,
required this.accessedCell,
Key? key,
}) : super(key: key);
final int index;
final int accessedCell;
@override
State<Tile> createState() => _TileState();
}
class _TileState extends State<Tile> {
bool _isAccessed = false;
@override
Widget build(BuildContext context) {
print(widget.accessedCell);
print(widget.index);
if (widget.accessedCell == widget.index) {
_isAccessed = true;
}
return Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5),
border: Border.all(color: _isAccessed ? Colors.blue : Colors.red),
),
child:
FittedBox(fit: BoxFit.contain, child: Text(widget.index.toString())),
);
}
}