如何为按钮小部件创建一个类

问题描述 投票:1回答:2

我将在我的flutter应用程序中有一堆按钮,我想为它创建一个类,所以我不需要复制粘贴它,并使我的代码看起来很长,相同类型的代码。我上课,没有问题,但我很挣扎,因为我希望每个按钮在按下时转到不同的页面。怎么做到这一点?

class thebuttonmaka extends StatelessWidget {
  final String texxt;
  final String buum;
  const thebuttonmaka(this.texxt);

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Padding(
      padding: EdgeInsets.only(top: 30),
      child: Material(
        elevation: 5,
        borderRadius: BorderRadius.circular(30),
        color: Colors.lightBlue,
        child: MaterialButton(
          minWidth: 250,
          padding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
          onPressed: WHAT TO PUT HERE?,
          child: Text(texxt,
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 20)
                  .copyWith(color: Colors.white, fontWeight: FontWeight.bold)),
        ),
      ),
    );
  }
}

所以我基本上需要帮助,我把放在这里的东西。我想将此选项添加到构造函数中,因此每当我调用该类时,我都可以将该按钮导航到该位置。示例thebuttonmaka('signup',signuppage)

dart flutter
2个回答
0
投票
class thebuttonmaka extends StatelessWidget {
  final String texxt;
  final String buum;
  final Function function; // add this
  const thebuttonmaka(this.texxt, this.function, this.buum); // change this

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Padding(
      padding: EdgeInsets.only(top: 30),
      child: Material(
        elevation: 5,
        borderRadius: BorderRadius.circular(30),
        color: Colors.lightBlue,
        child: MaterialButton(
          minWidth: 250,
          padding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
          onPressed: function, // add this here
          child: Text(texxt,
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 20)
                  .copyWith(color: Colors.white, fontWeight: FontWeight.bold)),
        ),
      ),
    );
  }
}

你可以像使用它一样

thebuttonmaka('signup',signuppage)

0
投票

您可以像这样定义您的类,并自定义关于按钮的所有内容(您也可以传递textalignment和样式,我只是展示一个示例) -

class CommonButton {
      static MaterialButton myButton(BuildContext context, int width, int l, int t, int r, int b, func, String text) {
        return MaterialButton(
              minWidth: width,
              padding: EdgeInsets.fromLTRB(l, t, r, b),
              onPressed: func,
              child: Text(text,
                  textAlign: TextAlign.center,
                  style: TextStyle(fontSize: 20)
                      .copyWith(color: Colors.white, fontWeight: FontWeight.bold)),
            );
      }
     }

如果你想在某个地方使用它,就这样称呼它 -

CommonButton.myButton(...)

(你必须明显通过onPressed功能)

© www.soinside.com 2019 - 2024. All rights reserved.