我有一个名为Classroom
的小部件,该小部件中有一个按钮,可将您导航到另一个名为ButtonPage
的页面。它只有一个按钮可以触发影响Classroom
状态的功能。完美运作。但是问题是我也想通过LightButton
小部件中的更新状态来更改Classroom
的颜色。这是代码。
class Classroom extends StatefulWidget {
@override
_ClassroomState createState() => _ClassroomState();
}
class _ClassroomState extends State<Classroom> {
bool isLightOn = false;
final List<String> lightColor = ["red", "green", "blue"];
String currentItem = "red";
void onButtonPress() {
setState(() {
isLightOn = isLightOn;
});
}
void selectItem(String selectedItem) {
setState(() {
currentItem = selectedItem;
});
}
Widget build(BuildContext context) {
return Container(
color: Colors.blue,
padding: EdgeInsets.all(5.0),
child: Column(
children: <Widget>[
LightBulb(
isLightOn: isLightOn,
currentItem: currentItem,
),
Container(
child: MaterialButton(
textColor: Colors.white,
color: Colors.blue,
child: Text("Go to button's page"),
onPressed: () {
Navigator.push(context,
MaterialPageRoute<void>(builder: (BuildContext context) {
return ButtonPage(
isLightOn: isLightOn,
onButtonPress: onButtonPress,
);
}));
},
),
),
LightColorSelector(
selectItem: selectItem,
currentItem: currentItem,
lightColor: lightColor,
),
],
),
);
}
}
class ButtonPage extends StatelessWidget {
final bool isLightOn;
final VoidCallback onButtonPress;
const ButtonPage({this.isLightOn, this.onButtonPress});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Button Page"),
),
body: Center(
child: Container(
child: LightButton(
isLightOn: isLightOn,
onButtonPress: onButtonPress,
),
)),
);
}
}
class LightButton extends StatelessWidget {
final bool isLightOn;
final VoidCallback onButtonPress;
const LightButton({this.isLightOn, this.onButtonPress});
@override
Widget build(BuildContext context) {
return Container(
color: Colors.red,
padding: EdgeInsets.all(5.0),
child: MaterialButton(
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
color: Colors.blue,
textColor: Colors.white,
child:
isLightOn ?? false ? Text("Turn light off") : Text("Turn light on"),
onPressed: () {
onButtonPress();
},
),
);
}
}
当我单击标记为MaterialButton
的{{1}}时,它将使用Go to button's page
和ButtonPage
变量将我导航到isLightOn
。在onButtonPress
中,当触发LightButton
时,它将仅重建上一页。这就是onButtonPress
的标签未更改的原因。如何使其受到影响?