我有一个有关发送setState
的基本问题
_GoToNextPage(){
Navigator.of(context).push(MaterialPageRoute(builder: (context) {...})
}
问题是,当我在第二页中更改背景颜色时,它没有 在同一页面中更改颜色,但是会更改主要首页的颜色。
这是完整的代码...
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(
home: SetStateToSecondPage(),
));
class SetStateToSecondPage extends StatefulWidget {
@override
_SetStateToSecondPageState createState() => _SetStateToSecondPageState();
}
class _SetStateToSecondPageState extends State<SetStateToSecondPage> {
Color color = Colors.deepPurpleAccent;
bool Switch = false;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: color,
appBar: AppBar(
title: Text('setState to Second Page ?'),
elevation: 0.0,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
RaisedButton(
onPressed: () {
setState(() {
Switch = !Switch;
color = Switch ? Colors.white : Colors.green;
});
},
child: Text('Change Back GroundColor'),
),
RaisedButton(
onPressed: () {
_GoToNextPage(context);
},
child: Text('To Next Page..'),
),
],
),
),
);
}
//------------- This is second Page ----------//
_GoToNextPage(BuildContext context) {
return Navigator.of(context).push(MaterialPageRoute(builder: (context) {
return Scaffold(
appBar: AppBar(
title: Text('Second Page'),
),
backgroundColor: color,
body: Center(
child: RaisedButton(
onPressed: () {
setState(() {
color = Colors.red;
});
},
child: Text('Change Back GroundColor'),
),
),
);
}));
}
}
谢谢
答案 0 :(得分:1)
SetState
特定于您所在的对象。当您调用它时,您会通知框架状态已更改。因此在_SetStateToSecondPageState
中调用setState不会影响第二页,因此您需要创建另一个StatefulWidget
class SecondPage extends StatefulWidget {
MaterialColor secondColor ;
SecondPage({this.secondColor});
@override
_SecondPageState createState() => new _SecondPageState();
}
class _SecondPageState extends State<SecondPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Second Page'),
),
backgroundColor: widget.secondColor,
body: Center(
child: RaisedButton(
onPressed: () {
setState(() {
widget.secondColor = Colors.amber;
});
},
child: Text('Change Back GroundColor'),
),
),
);
}
}
当您调用_GoToNextPage
时,请使用SecondPage
构造函数更改颜色
_GoToNextPage(BuildContext context) {
return Navigator.of(context).push(MaterialPageRoute(builder: (context) {
return SecondPage(
);
}));
}