我是应用程序开发的新手,遇到了问题。我的应用程序包含大约5-6个屏幕,所有屏幕都包含这样的脚手架小部件。
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFF332F43)
);
}
现在在所有的屏幕上,我有相同的概念和设计,所有的屏幕将共享相同的背景颜色。现在我在所有屏幕上都有一个按钮,即更改主题按钮和按钮点击该更改主题按钮,我想要更改所有的屏幕Scaffold小部件都要改变。现在我该如何实现这一目标?请帮助我解决我的问题。
Color color = Colors.blue; // make it at root level
void main() {
runApp(MaterialApp(home: Page1()));
}
在page1类中,导入上面的文件。
class Page1 extends StatefulWidget {
@override
_Page1State createState() => _Page1State();
}
class _Page1State extends State<Page1> {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: color,
appBar: AppBar(title: Text("Page 1")),
body: Center(
child: Column(
children: <Widget>[
RaisedButton(
onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (c) => Page2())),
child: Text("Go to Page 2"),
),
RaisedButton(
child: Text("Change color"),
onPressed: () => setState(() => color = Colors.red),
),
],
),
),
);
}
}
在page2类中,导入第一个文件。
class Page2 extends StatefulWidget {
@override
_Page2State createState() => _Page2State();
}
class _Page2State extends State<Page2> {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: color,
appBar: AppBar(title: Text("Page 2")),
body: Center(
child: Column(
children: <Widget>[
RaisedButton(
onPressed: () => Navigator.pop(context),
child: Text("Back"),
),
RaisedButton(
child: Text("Change color"),
onPressed: () => setState(() => color = Colors.green),
),
],
),
),
);
}
}