我有订单 orderList 列表。如果是Empty,则FloatingActionButton 是隐藏的。如果 orderList 有产品 - 将显示 FAB。我的代码:
bool statusFAB = false;
_getFABState(){
setState(() {
if(!orderList.isEmpty){
statusFAB = true;
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: _getFAB(),
backgroundColor: _kAppBackgroundColor,
body: Builder(
builder: _buildBody,
),
);
Widget _getFAB() {
if(statusFAB){
return FloatingActionButton(
backgroundColor: Colors.deepOrange[800],
child: Icon(Icons.add_shopping_cart),
onPressed: null);
}
}
Run Code Online (Sandbox Code Playgroud)
它不起作用,因为条件只起作用一次,但 orderList 的状态可以随时更改。
您不需要存储statusFAB变量,您可以即时评估它。请参阅下面的更新示例:
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: _getFAB(),
backgroundColor: _kAppBackgroundColor,
body: Builder(
builder: _buildBody,
),
);
Widget _getFAB() {
if (orderList.isEmpty) {
return Container();
} else {
return FloatingActionButton(
backgroundColor: Colors.deepOrange[800],
child: Icon(Icons.add_shopping_cart),
onPressed: null);
}
}
Run Code Online (Sandbox Code Playgroud)
嗯,有一个快捷方式可以与三元运算符一起使用,并且可以在 Stateful Widget 的 Scaffold 中使用,如下所示
floatingActionButton: orderList.isEmpty ? Container() : FloatingActionButton(...)
Run Code Online (Sandbox Code Playgroud)
除非你需要一个又长又复杂的函数,否则这很好用。即使你需要一个复杂的函数,那么只有在需要绘图时才可以调用该函数
floatingActionButton: orderList.isEmpty ? Container() : ComplicatedFn(...)
Widget ComplicatedFn() {
//.... Complicated Algo
return FloatingActionButton(...)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4066 次 |
| 最近记录: |