问题描述
我在Flutter中有两个图像,这些图像用于固定和取消固定列表视图中的数据,所以我的程序是,当我单击固定图像时,应该隐藏取消固定图像,而当我单击取消固定图像时,应该隐藏固定图像。那么如何在扑朔迷离中实现这件事。
这是我的演示代码
class PinUnpinData extends StatefulWidget {
@override
_PinUnpinDataState createState() => _PinUnpinDataState();
}
class _PinUnpinDataState extends State<PinUnpinData> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,title: Text(
"Pin-Unpin",style: TextStyle(fontSize: 20,color: Colors.white),),backgroundColor: Colors.white,body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,crossAxisAlignment: CrossAxisAlignment.center,children: <Widget>[
InkWell(
onTap: () {
},child: Padding(
padding: const EdgeInsets.all(20),child: Image.asset(
"assets/images/pin.png",height: 20,width: 20,)),InkWell(
onTap: () {},child: Image.asset(
"assets/images/unpin.png",))
],);
}
}
解决方法
创建局部变量以跟踪pinned
状态。然后使用setState()
方法在点击按钮时更新该变量的状态。另外,要显示相关图像,只需检查pinned
变量的值并显示相关图像,如果正确,则显示取消固定图像,否则显示固定图像。
class _PinUnpinDataState extends State<PinUnpinData> {
bool pinned = false; // to keep track if it's pinned or not
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,title: Text(
"Pin-Unpin",style: TextStyle(fontSize: 20,color: Colors.white),),backgroundColor: Colors.white,body: Center(
child: InkWell(
onTap: () {
setState(() {
pinned = pinned ? false : true; // check if pinned is true,if its true then set it false and voice versa
});
},child: Padding(
padding: const EdgeInsets.all(20),child: Image.asset(
pinned
? "assets/images/unpin.png" //show this image when it's pinned
: "assets/images/pin.png",// show this image when it not pinned
height: 20,width: 20,)),);
}
}