我想知道如何根據動作(例如:onPressed
)銷燬/重新創建Widget
。如何在動作後處置/重新創建Widget
我想到這個的方法是讓我的Widget在Opacity
對象內被敲擊,並根據用戶在我的應用中的某處進行交互來控制對象的狀態(即:隱藏/顯示小部件而不是處理/重新創建)。但是,我在這裏問的是,如何在單擊按鈕後銷燬/重新創建Widget?
我已經創建了下面的虛擬示例來展示我的意思。
當我按下雲Icon
並按下RaisedButton
時重新創建了紅色Icon
。
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Destroy/Recreate Example"),
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Stack(fit: StackFit.passthrough,
children: <Widget>[
new IconButton(icon: new Icon(
Icons.cloud_circle, size: 40.0, color: Colors.blue,),
onPressed: null /*_destroyWidget*/),
new Positioned(child: new DecoratedBox(
decoration: new BoxDecoration(shape: BoxShape.circle),
child: new Icon(
Icons.add_circle, size: 20.0, color: Colors.red,),),
top: 3.0,
left: 3.0)
],
),
new RaisedButton(onPressed: null /*_recreateWidget*/,
child: new Text("Recreate!"),
),
])
)
);
}
如何開始這個想法?
更新
下面的代碼實現了同樣的事情,但通過操縱紅色Icon
(顯示/隱藏)的Opacity
。
var _myOpacity = 0.0;
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Destroy/Recreate Example"),
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Stack(fit: StackFit.passthrough,
children: <Widget>[
new IconButton(icon: new Icon(
Icons.cloud_circle, size: 40.0, color: Colors.blue,),
onPressed:()=>setState((){
_myOpacity =0.0;
}) /*_destroyWidget*/),
new Positioned(child: new Opacity(
opacity: _myOpacity,
child:
new DecoratedBox(
decoration: new BoxDecoration(shape: BoxShape.circle),
child: new Icon(
Icons.add_circle, size: 20.0, color: Colors.red,),),),
top: 3.0,
left: 3.0)
],
),
new RaisedButton(onPressed:()=>
setState((){
_myOpacity = 1.0;
})
/*_recreateWidget*/,
child: new Text("Recreate!"),
),
])
)
);
}
目的是什麼。你爲什麼要摧毀和重建?如果你想更新視圖,調用'setState()'應該做你想要的。例如見https://codelabs.developers.google.com/codelabs/flutter/index.html#5 –
真的出於好奇。但爲了回答你的問題,我想到了用戶在商店中訂購某些東西的場景。將雲圖標視爲您的購物車,並將其重新添加按鈕稱爲「添加到購物車」,同時按下紅色圖標,就好像「您的購物車中有物品」一樣。然後當你完成添加東西時,你點擊購物車,一個應該刪除紅色圖標的動作。 我明白如何通過操縱狀態來實現相同的行爲,我添加了一個更新的帖子,我通過操作「不透明度」來顯示相同的行爲。 – aziza
如果下面的答案沒有回答你的問題,那麼給答案添加評論可能是一個好主意,以便Collin得到通知。 –