在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<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'),
),
),
);
}
}
hide_show.gif
ps:如果还有别的方案,麻烦告知下,谢谢!
每天学一点,学到Flutter发布正式版!
网友评论
GestureDetector中有一个behavior 是用于控制透明情况下是否可以响应点击事件的