【问题标题】:Flutter redraw appbarFlutter 重绘应用栏
【发布时间】:2018-12-20 21:59:39
【问题描述】:

我正在创建一个应用栏,如果设备连接到互联网,它应该会改变颜色。该栏在未连接时应该是红色的,在连接时应该是蓝色的。一切正常,但在我导航到新页面之前更改不会出现。我希望立即进行此更改。

这是我的代码:

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;
  }
}

你们中的任何人都知道我怎样才能让这个立即更新吗?

【问题讨论】:

    标签: flutter


    【解决方案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);
        //   })
        // })
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-23
      • 2018-12-08
      • 2019-10-29
      • 1970-01-01
      • 2022-01-18
      • 2020-12-15
      • 2018-12-30
      相关资源
      最近更新 更多