【发布时间】:2018-10-07 13:09:51
【问题描述】:
我有一个有状态的小部件,它有一个简单的网格,每个网格单元都有一个容器。
我想点击一个单元格/容器并更改其内容。
问题在于 GestureDetector -> onTap 方法会在所有 cel 的应用刷新时触发。
在下面的示例中,_changeCell 方法会立即为所有 cel 触发,onTap 不起作用。
有什么想法吗?
import 'package:flutter/material.dart';
class GridWidget extends StatefulWidget {
@override
_GridWidgetState createState() => new _GridWidgetState();
}
class _GridWidgetState extends State<GridWidget> {
@override
Widget build(BuildContext context) {
Color cellColor = Colors.white;
Text cellText = new Text('');
// when a cell is tapped, change the color and text
_changeCell(index) {
setState(() {
cellColor = Colors.lightBlue;
cellText = new Text('clicked');
});
print("Container clicked " + index.toString());
}
// create a 5 by 5 grid
return new GridView.count(
crossAxisCount: 5,
children: new List.generate(5, (index) {
return new GestureDetector(
onTap: _changeCell(index),
child: new Container(
width: double.infinity,
height: double.infinity,
decoration: new BoxDecoration(
color: cellColor,
),
child: new Center(
child: cellText,
),
),
);
}),
);
}
}
【问题讨论】: