如何在Flutter中访问GridView中特定项目的索引?

时间:2019-07-04 10:38:18

标签: flutter dart

我正在使用GridView.builder,其中包含25个项目,并且我想在起始项目上使用GestureDetector。我将如何访问该项目?

这是我了解的:

int currD, currM, currY;
scanf("%d/%d/%d", &currD, &currM, &currY);

这是包含25个项目的代码,我想访问其中一个

 int x, y = 0;
  x = (index / gridStateLength).floor();
  y = (index % gridStateLength);

1 个答案:

答案 0 :(得分:2)

如何将GestureDetector添加到每个项目并调用以索引为参数的函数呢? (在浏览器中写在这里的代码:-))

class Grid4 extends StatelessWidget {
  void tapped(int index){
    if(index == 1){
      print("huray 1");
    } else {
      print("not the one :(");
    }
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Container(
        padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 10),
        color: Colors.orange,
        child: GridView.builder(
          itemCount: 25,
          itemBuilder: (context, index) =>
              GestureDetector(
                  onTap: () => tapped(index),
                  child: Container(decoration: BoxDecoration(
                          color: Colors.white70, shape: BoxShape.circle))),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 5,
            mainAxisSpacing: 40,
            crossAxisSpacing: 50,
          ),
        ),
      ),
    );
  }
}