如何检查按钮是不是被按下
Posted
技术标签:
【中文标题】如何检查按钮是不是被按下【英文标题】:How to check if a button is pressed如何检查按钮是否被按下 【发布时间】:2020-01-02 14:44:49 【问题描述】:我需要一个点赞按钮,点击一次会增加点赞数,第二次点击会减少点赞数,如何判断按钮是否被点击
这是我的客户颤振小部件练习
按钮小部件
lass ButtonBuilder extends StatefulWidget
final Icon icon;
ButtonBuilder(this.icon,);
_ButtonBuilderState createState()=>_ButtonBuilderState(this.icon);
class _ButtonBuilderState extends State<ButtonBuilder>
final Icon _icon;
_ButtonBuilderState(this._icon);
final _bloc=ButtonCounterBloc();
@override
Widget build(BuildContext context)
return RootButton(
child: StreamBuilder(
stream: _bloc.counter,
initialData: 0,
builder: (BuildContext context,AsyncSnapshot snapshot)
return _buildButton(_icon,'$snapshot.data');
,
),
);
_buildButton(Icon _icon,String _text)
return Column(
children: <Widget>[
IconButton(
icon: _icon,
onPressed: ()=>_bloc.buttonEventSink.add(FirstOnPressedEvent()),
),
Text(_text),
],
);
main.dart
class MyHomePage extends StatefulWidget
MyHomePage(Key key, this.title) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
class _MyHomePageState extends State<MyHomePage>
@override
Widget build(BuildContext context)
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ButtonBuilder(icon: Icon(Icons.thumb_up),),
ButtonBuilder(icon: Icon(Icons.thumb_down),),
],
),
),
);
我不知道如何检查按钮是否被点击
【问题讨论】:
简单地使用一个布尔变量initialy一旦按下使其为真再次按下时检查它是否已经为真然后将其设为假 【参考方案1】:您可以将名为 isPressed
的标志最初设置为 false
,每次按下按钮时都会取消该标志。
而在onPressed
回调中,你可以根据变量编写不同的逻辑。
但您应该记住,在下面的示例中,一旦按钮宽度的 State
被释放,_isPressed
变量将被重置。
如果您希望有一个持久按钮,您可以在ButtonCounterBloc
中添加一个类似的参数,并将其值分配给initState
类的initState
方法中的_isPressed
。
这样,即使应用重新启动或状态被释放并再次挂载,您的按钮也会保持不变。
class ButtonBuilder extends StatefulWidget
final Icon icon;
ButtonBuilder(this.icon,);
_ButtonBuilderState createState()=>_ButtonBuilderState(this.icon);
class _ButtonBuilderState extends State<ButtonBuilder>
final Icon _icon;
_ButtonBuilderState(this._icon);
final _bloc=ButtonCounterBloc();
bool _isPressed = false;
@override
Widget build(BuildContext context)
return RootButton(
child: StreamBuilder(
stream: _bloc.counter,
initialData: 0,
builder: (BuildContext context,AsyncSnapshot snapshot)
return _buildButton(_icon,'$snapshot.data');
,
),
);
_buildButton(Icon _icon,String _text)
return Column(
children: <Widget>[
IconButton(
icon: _icon,
onPressed: ()
setState(()
_isPressed = !_isPressed;
);
if(_isPressed)
// This block will be executed when button is pressed odd number of times.
_bloc.buttonEventSink.add(FirstOnPressedEvent());
else
// This block will be executed when button is pressed even number of times;
),
Text(_text),
],
);
【讨论】:
以上是关于如何检查按钮是不是被按下的主要内容,如果未能解决你的问题,请参考以下文章