如何知道Flutter中点击了哪个按钮? [英] How to know which button is tapped in Flutter?

查看:347
本文介绍了如何知道Flutter中点击了哪个按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了这个问题:如何识别哪个按钮在颤抖中被点击

但是,还有什么更好的方法来检测哪个按钮被点击了吗? 前任. 我通过for循环创建了100个按钮,然后如何知道?在iOS中,我们使用的是 tag 属性,因此,如果存在这种选项,那么将非常易于检测.

But Is there any better way to detect which button is tapped? Ex. I created 100 button via for loop then how to know? In iOS we are using tag property so If there is this kind of option then it will really handy to detect.

下面是我的代码

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;               
     });
  }

推荐答案

为每个按钮分配不同的回调

Assign to each button a different callback

void onPress(int id) {
  print('pressed $id');
}

Widget build(BuildContext context) {
  return Row(
    children: [
      RaisedButton(onPressed: () => onPress(0),),
      RaisedButton(onPressed: () => onPress(1),),
    ],
  );
}

这篇关于如何知道Flutter中点击了哪个按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆