如何为按钮小部件创建类

时间:2019-04-12 07:38:52

标签: dart flutter

在我的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)

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

您可以像这样定义您的类并从字面上自定义按钮的所有内容(您也可以传递文本对齐方式和样式,我只是显示一个示例)-

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函数)