我遇到了这个问题:How to identify which button is clicked in flutter
但是还有什么更好的方法来检测哪个按钮被点击了吗? 例如 我通过for循环创建了100个按钮,然后如何知道?在iOS中,我们使用的是 tag 属性,因此,如果存在这种选项,那么将非常易于检测。
已编辑:
下面是我的代码
List<Widget> pageCurrentPageIndicator(int currentIndex, int totoalCount) {
List<Widget> tempWidget = new List<Widget>();
for (var i = 0; i < totoalCount; i++) {
Container container = Container(
width: 47.0,
height: 30.0,
child: FlatButton(
child: Image.asset(
(i == currentIndex
? 'lib/assets/radioBtnActive.png'
: 'lib/assets/radioBtn.png'),
fit: BoxFit.contain), onPressed: () {
whichButtonistaped(i);
},
)
);
tempWidget.add(container);
}
return tempWidget;
}
void whichButtonistaped(int btnTag){
print(btnTag);
setState(() {
currentBannerIndex = btnTag;
});
}
答案 0 :(得分:1)
为每个按钮分配不同的回调
void onPress(int id) {
print('pressed $id');
}
Widget build(BuildContext context) {
return Row(
children: [
RaisedButton(onPressed: () => onPress(0),),
RaisedButton(onPressed: () => onPress(1),),
],
);
}
答案 1 :(得分:1)
我建议使用小部件的key
属性。
这是一个解决方案:
Widget build(BuildContext context) {
return Row(
children: [
TagButton(onPressed: (k) => onPress(k)),
TagButton(onPressed: (k) => onPress(k)),
],
);
}
void onPress(Key id) {
print('pressed $id');
}
使用以下自定义小部件:
typedef TagButtonPressedCallBack = void Function(Key key);
class TagButton extends StatelessWidget {
final TagButtonPressedCallBack onPressed;
agButton({
this.onPressed,
}) : super(key: UniqueKey());
@override
Widget build(BuildContext context) {
return RaisedButton(onPressed: () {
if (onPressed != null) onPressed(key);
});
}
}
输出:
I/flutter ( 6371): pressed [#2ca50]
I/flutter ( 6371): pressed [#2180d]
I/flutter ( 6371): pressed [#2ca50]
该解决方案为您提供TagButton
小部件的唯一标识符。
如果要将RaisedButton
的ID放在TagButton
内,则可以在Key
方法中生成build
并将其传递给RaisedButton
像这样:
typedef TagButtonPressedCallBack = void Function(Key key);
class TagButton extends StatelessWidget {
final TagButtonPressedCallBack onPressed;
TagButton({
Key key,
this.onPressed,
}) : super(key: key);
@override
Widget build(BuildContext context) {
var k = UniqueKey();
return RaisedButton(
key: k,
onPressed: () {
if (onPressed != null) onPressed(k);
});
}
}
答案 2 :(得分:1)
没有很多可用的解决方案,而可用的解决方案是对我来说不起作用的静态按钮。这是我在有效的项目中为多个动态FloatingActionButtons做的事情
为每个按钮分配动态ID的自定义按钮类:
class FAB extends StatelessWidget {
final int id;
final Function(int) onPressed;
final String buttonText;
const FAB({this.id, this.onPressed, this.buttonText});
@override
Widget build(BuildContext context) {
return FloatingActionButton(
onPressed: () {onPressed(this.id);},
backgroundColor: Colors.blue,
child: new Text(this.buttonText,
style: new TextStyle(fontSize: 25.0))
);
}
}
使用上面的类创建按钮:
new FAB(
id: id,
onPressed: buttonFunction,
buttonText: 'Button Text'
)
按钮功能:
buttonFunction(id) {
print('Button id: $id');
}