1

I made a GridView with children that each has a GestureDetector and a onTap method set. But the onTap event gets called only when the view is created and not when the item has been tapped. What am I doing wrong here?

class MyGridView extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return new Column(
        children: <Widget>[
          new Expanded(
              child: new GridView.count(
                  crossAxisCount: 2,
                  children: [
                    new GridItem(0),
                    new GridItem(1)
                  ]
              )
          )
        ]
    );
  }
}

class GridItem extends StatelessWidget {
  final int code;
  GridItem(this.code);

  @override
  Widget build(BuildContext context) {
    return new GestureDetector(
        onTap: print(code),
        child: new Container(
            height: 48.0,
            child: new Text('$code')
        )
    );
  }
}
4

1 回答 1

6

你要:

onTap: () { print(code); },

您正在做的是调用 print,然后将 print 的返回值(将为 null)保存为 onTap 处理程序,这实际上禁用了 onTap 处理程序。如果您在日志中看到任何内容,那将是您实际进行构建的时间,而不是您点击的时间。

于 2017-03-12T04:36:10.050 回答