我正在使用GridTile在GridView中创建每个项目。每个项目都是从数据列表中动态创建的。我需要通过获取键或索引来找出单击了哪个项目。请任何人提出一种方法?

这是我的代码

 new GridView.count(
                    shrinkWrap: true,
                    primary: false,
                    childAspectRatio: 2.0,
                    crossAxisCount: 3,
                    mainAxisSpacing: 10.0,
                    children: _kCategoryTiles.map((_FilterItemTile item) {
                      return new GridTile(
                        child: new Container(
                          alignment: Alignment.center,
                          decoration: new BoxDecoration(
                            shape: BoxShape.rectangle,
                            borderRadius: new BorderRadius.all(
                                new Radius.elliptical(10.0, 20.0)),
                            border: new Border.all(
                              color: const Color(0xFF33b17c),
                            ),
                          ),
                          margin: new EdgeInsets.all(10.0),
                          child: new Text(
                            item.itemName,
                            textAlign: TextAlign.center,
                            style: new TextStyle(
                              color: Colors.black,
                              fontSize: 12.0,
                              fontFamily: 'helvetica_neue_medium',
                              letterSpacing: 0.59,
                            ),
                          ),
                        ),
                      );
                    }).toList(),
                  )

提前致谢。

最佳答案

您可以将GridTile包装在FlatButton中,它为您提供onPressed属性。您可以在其中访问_FilterItemTile item:

return new GridView.count(
    shrinkWrap: true,
    primary: false,
    childAspectRatio: 2.0,
    crossAxisCount: 3,
    mainAxisSpacing: 10.0,
    children: _kCategoryTiles.map((_FilterItemTile item) {
        return new FlatButton(
    onPressed: () {
        // add code here
        print(item);
        someFunction(item);
    },
    child: new GridTile(
        child: new Container(
            alignment: Alignment.center,
            decoration: new BoxDecoration(
            shape: BoxShape.rectangle,
            borderRadius: new BorderRadius.all(
                new Radius.elliptical(10.0, 20.0)),
            border: new Border.all(
                color: const Color(0xFF33b17c),
            ),
            ),
            margin: new EdgeInsets.all(10.0),
            child: new Text(
            item.itemName,
            textAlign: TextAlign.center,
            style: new TextStyle(
                color: Colors.black,
                fontSize: 12.0,
                fontFamily: 'helvetica_neue_medium',
                letterSpacing: 0.59,
            ),
            ),
        ),
        );
        )
    }).toList(),
),

08-05 09:06