Flutter 设置控件是否可见

更新日期: 2020-01-20阅读: 2.2k标签: 控件

共有两种实现比较简单的方式

第一种比较好理解,将一个控件的透明度设置成0,打到隐藏的目的。

class _HideAndShowPageState extends State<HideAndShowPage> {
bool visible = true;

@override
Widget build(BuildContext context) {
  return new Scaffold(
    appBar: new AppBar(
      title: new Text('widget显示与隐藏'),
      centerTitle: true,
    ),
    body: new ListView(
      children: <Widget>[
        new Padding(
          padding: const EdgeInsets.only(left: 10.0, top: 10.0, right: 10.0),
          child: new RaisedButton(
              textColor: Colors.black,
              child: new Text(visible ? '隐藏B    显示A' : '隐藏A   显示B'),
              onPressed: () {
                visible = !visible;
                setState(() {});
              }),
        ),
        new Padding(
          padding: const EdgeInsets.only(left: 10.0, top: 10.0, right: 10.0),
          child: new Stack(
            children: <Widget>[
              new TestAWidget(
                visible: visible,
              ),
              new TestBWidget(
                visible: !visible,
              ),
            ],
          ),
        ),
      ],
    ),
  );
}
}

class TestAWidget extends StatelessWidget {
final bool visible;

const TestAWidget({Key key, this.visible}) : super(key: key);

@override
Widget build(BuildContext context) {
  return AnimatedOpacity(
    duration: Duration(milliseconds: 300),
    opacity: visible ? 1.0 : 0.0,
    child: new Container(
      color: Colors.blue,
      height: 100.0,
      child: new Center(
        child: new Text('TestAWidget'),
      ),
    ),
  );
}
}

class TestBWidget extends StatelessWidget {
final bool visible;

const TestBWidget({Key key, this.visible}) : super(key: key);

@override
Widget build(BuildContext context) {
  return AnimatedOpacity(
    duration: Duration(milliseconds: 300),
    opacity: visible ? 1.0 : 0.0,
    child: new Container(
      color: Colors.green,
      height: 100.0,
      child: new Center(
        child: new Text('TestBWidget'),
      ),
    ),
  );
}
}


第二种办法是使用 SDK 自带的 Offstage 控件包裹。

offstage的布局行为完全取决于 offstate 参数,offstage 默认为 true ,不显示;

当 offstage 为 true,child 不会绘制到屏幕上,不会响应点击事件,也不会占用空间; 当 offstage 为 false,child 绘制到屏幕上; 注意,当 offstage 不可见,如果 child 有动画,应该手动停止动画, offstage 不会停止动画;

class TestCWidget extends StatelessWidget {
 final bool visible;

 const TestCWidget({Key key, this.visible}) : super(key: key);

 @override
 Widget build(BuildContext context) {
   return new Offstage(
     offstage: visible,
     child:new Container(
       color: Colors.orange,
       height: 100.0,
       child: new Center(
         child: new Text('TestCWidget'),
       ),
     ),
   );
 }
}

了解更多有深度技术文章,与移动端、大前端未来方向的认知, 前往订阅 开源实验室小专栏。

原文 https://www.kymjs.com/note/2020/03/19/01/

链接: https://www.fly63.com/article/detial/8320

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!