在Flutter中没有removeView,addView这种方式控制Widget Tree中的组件

场景: 根据状态显示隐藏widget

解决方案1(占位):

Widget _buildA() {

var content;

if (data?.isNotEmpty) {

//如果数据不为空,则显示Text

content = new Text('数据不为空');

} else {

//当数据为空我们需要隐藏这个Text

//我们又不能返回一个null给当前的Widget Tree

//只能返回一个长宽为0的widget占位

content = new Container(height:0.0,width:0.0);

}

return content;

}

解决方案2(透明度):

class _HideAndShowPageState extends State {

bool visible = true;

@override

Widget build(BuildContext context) {

return new Scaffold(

appBar: new AppBar(

title: new Text('widget显示与隐藏'),

centerTitle: true,

),

body: new ListView(

children: [

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: [

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'),

),

),

);

}

}

解决方案3(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'),

),

),

);

}

}

showandhide.gif

ps:如果还有别的方案,麻烦告知下,谢谢!

已有项目集成到Flutter代码已经上传到我的GITHUB

知乎日报Flutter版代码已经上传到我的GITHUB

基础学习过程中的代码都放在GITHUB

每天学一点,学到Flutter发布正式版!

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐