如何在颤振中重建父小部件?

时间:2021-06-15 13:42:40

标签: flutter dart

这是一个测试,如果子容器为绿色,则父小部件变为绿色。

它们一开始都是蓝色的,当点击孩子时,两者都应该变成绿色。

孩子被按下时会改变颜色。

class ColoredSquare extends StatelessWidget {
      ColoredButton button = ColoredButton();
      @override
      Widget build(BuildContext context) {
        return Scaffold(body: Column(children: [

        button, 
        Container(width: 50, height: 50, color: button.color == Colors.blue ? Colors.blue : Colors.green,)]
 ) );

  }


}

class ColoredButton extends StatefulWidget {
  Color color = Colors.blue;    
  @override
  _TestState createState() => _ColoredButtonState();
}

class _ColoredButtonState extends State<Test> {

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onTap: (){setState(() {
          widget.color = Colors.green;

        });}

        ,child: Container(width: 50, height: 50, color: widget.color,));

  }
}

问题是,如果我通过单击更改我的子小部件的状态(颜色),它的状态将更新,这意味着它会改变颜色就好了。但是,父级将保持相同的颜色,因为它没有重建,它不知道子级已更新。

如何强制父级重建?

1 个答案:

答案 0 :(得分:0)

传递一个函数给child,返回click事件调用给parent,parent会更新自己和child的颜色。

矩形类

class Rectangle extends StatefulWidget {
  @override
  _RectangleState createState() => _RectangleState();
}

class _RectangleState extends State<Rectangle> {
  Color color = Colors.blue;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
      child: Column(mainAxisSize: MainAxisSize.min, children: [
        Test(
          color: color,
          onTap: () {
            print('Rectangle called');
            setState(() {
              color = Colors.green;
            });
          },
        ),
        Container(
          width: 50,
          height: 50,
          color: color,
        )
      ]),
    ));
  }
}

测试类

class Test extends StatefulWidget {
  final Function() onTap;
  Color color;

  Test({Key? key, required this.onTap, required this.color}) : super(key: key);

  @override
  _TestState createState() => _TestState();
}

class _TestState extends State<Test> {
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onTap: () {
          print('Test called');
          widget.onTap();
        },
        child: Container(
          width: 50,
          height: 50,
          color: widget.color,
        ));
  }
}