这是一个测试,如果子容器为绿色,则父窗口小部件将变为绿色。
它们一开始都是蓝色的,当单击子项时,它们都应该变成绿色。
当孩子被按下时,它会改变颜色。
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,));
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,如果我通过单击子部件来更改其状态(颜色),它的状态将会更新,这意味着它会很好地改变颜色。但是,父级将保持相同的颜色,因为它没有重建,它不知道子级已更新。
我怎样才能强迫父母重建?
将函数传递给子级并将单击事件调用返回给父级,父级将更新其自身和子级的颜色。
矩形类
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,
)
]),
));
}
}
Run Code Online (Sandbox Code Playgroud)
测试班
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,
));
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4172 次 |
最近记录: |