我正在创建一个应用栏,如果设备未连接到互联网,该栏应该会更改颜色。如果未连接,则该条应为红色,而连接时,该条应为蓝色。一切正常,但是在导航到新页面之前不会显示更改。我希望这种变化马上发生。
这是我的代码:
class MyAppBar extends AppBar {
static AppBarChoices choices = new AppBarChoices();
MyAppBar({Key key, Widget title})
: super(key: key, title: title, backgroundColor: choices.getColor() , actions: <Widget> [choices.getText(), choices.getIcon()]);
}
class AppBarChoices {
App app = new App();
Color _color = new Color(0xff023570);
Icon _icon = new Icon(Icons.wifi);
Text _text = new Text('');
updateAppBar(bool isOnline){
if (isOnline){
_color = new Color(0xff023570);
_icon = new Icon(Icons.wifi);
_text = new Text('');
} else {
_color = new Color(0xffD0021B);
_icon = new Icon(Icons.signal_wifi_off);
_text = new Text('no internet accsess');
}
}
getColor(){
return _color;
}
getIcon(){
return _icon;
}
getText(){
return _text;
}
}
你们中的任何人都知道我如何立即更新它?
答案 0 :(得分:1)
永远不要扩展小部件。相反,您应该使用合成。
然后,按照此原则,您应该将小部件转换为StatefulWidget
,并在连接更改时调用setState
。
class MyAppBar extends StatefulWidget implements PreferredSizeWidget {
@override
_MyAppBarState createState() => _MyAppBarState();
@override
Size get preferredSize => Size.fromHeight(kToolbarHeight);
}
class _MyAppBarState extends State<MyAppBar> {
Color _color = new Color(0xff023570);
Icon _icon = new Icon(Icons.wifi);
Text _text = new Text('');
@override
void initState() {
watchConnectionStateChange();
super.initState();
}
@override
Widget build(BuildContext context) {
return AppBar(
backgroundColor: _color,
actions: <Widget>[_text, _icon],
);
}
void watchConnectionStateChange() {
// TODO: watch connectionStateChange
// connection.onChange((value) {
// setState(() {
// color = value == hasInternet ? Color(0xff023570) : Color(0xffD0021B);
// })
// })
}
}