通过InkWell onTap从其父级更改材料的颜色属性

时间:2018-09-21 11:09:41

标签: dart flutter

我创建了一个具有InkWell子级的窗口小部件,并且想在敲击InkWell子级时更改该窗口小部件的颜色。目前,我在InkWell类中有一个_pressed变量来控制小部件的颜色:

class ButtonA extends StatefulWidget {
   ButtonA();
   @override
   State createState() => new ButtonAState();
}

class ButtonAState extends State<ButtonA> {
   bool _pressed = false;
   Widget build(BuildContext context){
      return new Expanded(
        child: new Material(
            color: _pressed ? Colors.greenAccent : Colors.redAccent,
            child: new InkWell(
                onTap: () => (
                   this.setState((){
                   _pressed = true;
               })),
            ),
          ),
        ),
       }

在父级中,我只需导入ButtonA并按以下方式创建它:

new Button()

由于我希望链接到此轻敲行为的功能越来越多,我希望能够更改父类中的按钮颜色。我正在考虑将tap函数传递给Button类,以便具有类似以下内容:

class ButtonA extends StatefulWidget {
   VoidCallback _tap;

   ButtonA(this._tap);
   @override
   State createState() => new ButtonAState();
}

和InkWell将是:

child: new InkWell(onTap: () => _tap())

在父类中,我将有一个tap函数,用于操纵按钮的颜色并做其他事情。

我应该如何将按钮的状态传递给它的父按钮,以便我可以做类似的事情

  this.colors = Colors.white

在父班?有可能吗?

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

    class ButtonA extends StatefulWidget {

        VoidCallback tap;
        Color defaultColor;
        Color pressedColor;
        ButtonA({this.tap, this.pressedColor, this.defaultColor});

       ButtonA();
       @override
       State createState() => new ButtonAState();
    }

    class ButtonAState extends State<ButtonA> {
       bool _pressed = false;
       Widget build(BuildContext context){
          return new Expanded(
            child: new Material(
                color: _pressed ? widget.pressedColor : widget.defaultColor,
                child: new InkWell(
                    onTap: () { 
                        widget.tap();
                        this.setState((){
                       _pressed = true;
                   });

                   },
                ),
              ),
            ),
           }

用法:

    ButtonA(
        tap: () {

           //your logic from your parent
        },

        defaultColor: Colors.white,
        pressedColor: Colors.blue

    );       
相关问题