flutter - Flutter - 从自定义小部件返回 onTap 并执行动画
问题描述
我有一个名为 RowItem 的自定义小部件,它是一个有状态的小部件。当用户单击它动画的小部件时。但是我也想将 onTap 事件返回给父小部件,但我不知道该怎么做......
这是我的 RowItem 小部件:
class _RowItemState extends State<RowItem> {
bool isSelected = false;
double underlineWith = 0;
@override
Widget build(context) {
// Pass the text down to another widget
return new GestureDetector(
onTap: () {
isSelected = !isSelected;
if (isSelected) {
setState(() {
underlineWith = 18.0;
});
} else {
setState(() {
underlineWith = 0;
});
}
},
child: new Column(
children: <Widget>[
new Padding(
padding: EdgeInsetsDirectional.fromSTEB(8.0, 0.0, 8.0, 0.0),
child: new Container(
child: new Text(
widget.text,
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
softWrap: true,
style: TextStyle(
fontSize: 12.0,
fontWeight: FontWeight.bold,
color: Color(0x99222222)),
),
)),
new Padding(
padding: EdgeInsetsDirectional.fromSTEB(0.0, 5.0, 0.0, 10.0),
child: new AnimatedContainer(
height: 2,
width: underlineWith,
color: widget.underlineColor,
duration: Duration(milliseconds: 150),
),
),
],
),
);
}
}
如果我想返回 onTap 事件,我可以这样做:
return new GestureDetector(
onTap: widget.onTap
}
但是我怎么能同时做动画和返回 onTap 事件呢?
我想在点击RowItem时运行代码:
new GridView.builder(
physics: const NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: _subCategories.length,
gridDelegate:
new SliverGridDelegateWithFixedCrossAxisCount(
childAspectRatio: 3.2,
crossAxisCount: 3),
itemBuilder: (BuildContext context, int index) {
return new RowItem(
text: _subCategories[index],
underlineColor: Color(0xff73A6AD),
onTap: () {
setState(() {
//do something;
});
},
);
}
)
解决方案
在 RowItem 内部创建一个函数 handleOnTap()。在这个函数中你更新你的值和 setState 然后调用 widget.onTap()
func handleOnTap() {
isSelected = !isSelected;
if (isSelected) {
setState(() {
underlineWith = 18.0;
});
} else {
setState(() {
underlineWith = 0;
});
}
widget.onTap();
}
推荐阅读
- javascript - 如何在 Qunit 测试框架中检查代码覆盖率
- r - 如何根据观察的出现来更改观察的名称
- java - 一个区域的慢速 JCS 缓存
- blockchain - 如何从 Substrate 私有节点提取奖励?
- spring - RestTemplate 在 Spring Boot 中为 Null
- solidity - 将solidity余额迁移为从合约A到B的映射
- php - 会员登录后重定向回 URL
- python - NsLookup 打印出清理
- unity3d - Unity UI:你能同时锚定到一个特定的点,并在各个方向上伸展吗?
- reactjs - 将打字稿传递函数作为道具反应并从子组件调用