在Flutter中沒有removeView,addView這種方式控制Widget Tree中的組件
場(chǎng)景: 根據(jù)狀態(tài)顯示隱藏widget
解決方案1(占位):
Widget _buildA() {
var content;
if (data?.isNotEmpty) {
//如果數(shù)據(jù)不為空,則顯示Text
content = new Text('數(shù)據(jù)不為空');
} else {
//當(dāng)數(shù)據(jù)為空我們需要隱藏這個(gè)Text
//我們又不能返回一個(gè)null給當(dāng)前的Widget Tree
//只能返回一個(gè)長(zhǎng)寬為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'),
),
),
);
}
}
解決方案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