gpt4 book ai didi

flutter - 如何在flutter中重建父控件?

转载 作者:行者123 更新时间:2023-12-03 08:20:35 29 4
gpt4 key购买 nike

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

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

按下时子项会改变颜色。

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

}
}

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

如何强制父级重建?

最佳答案

将函数传递给子级并将点击事件调用返回给父级,父级将更新其自身和子级的颜色。

矩形类

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

关于flutter - 如何在flutter中重建父控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67987471/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com