Flutter:更新同级小部件的状态
问题内容:
如何在Flutter中更新同级小部件的状态?
例如,如果我有一个矩形小部件,则可以通过调用setState()
并更改color变量(如下面的“ Turn
Green”按钮那样)来从小部件内更改其颜色。但是,说我想要一个在矩形外部的按钮,它将改变其颜色。我该如何与Rectangle交流该更改其颜色以及更改为哪种颜色的时间?
这是我的示例代码。当用户按下“ Turn Blue”按钮时,我希望矩形变为蓝色,但是我无法从同级窗口小部件访问其状态。
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Hello Rectangle',
home: Scaffold(
appBar: AppBar(
title: Text('Hello Rectangle'),
),
body: Column(
children: <Widget>[
HelloRectangle(),
FlatButton(
child: Text('Turn Blue!',
style: TextStyle(fontSize: 40.0),
textAlign: TextAlign.center,
),
onPressed: () {
// How to update state of the Rectangle from here?
},
),
]
),
),
),
);
}
class HelloRectangle extends StatefulWidget {
@override
HelloRectangleState createState() {
return new HelloRectangleState();
}
}
class HelloRectangleState extends State<HelloRectangle> {
Color _color;
@override
void initState() {
super.initState();
_color = Colors.red;
}
@override
Widget build(BuildContext context) {
return Center(
child: Container(
color: _color,
height: 400.0,
width: 300.0,
child: Center(
child: FlatButton(
child: Text('Turn Green!',
style: TextStyle(fontSize: 40.0),
textAlign: TextAlign.center,
),
onPressed: () {
// I can update the state from here because I'm inside the widget
setState(() {
_color = Colors.green;
});
},
),
),
),
);
}
}
问题答案:
经验法则是,您不能访问层次结构中不在您之上的任何窗口小部件的状态。因此,基本上,我们需要将状态(颜色)上移到祖先。介绍一个StatefulWidget,它可以构建Scaffold或Column并在其中存储矩形颜色。现在,矩形小部件不再需要存储颜色,因此可以成为无状态小部件-
您可以通过构造函数传递颜色。现在,两个onPressed回调都可以在新的StatefulWidget上调用setState的方法。(除其他方法外,您还可以将该方法传递给矩形小部件。)