簡體   English   中英

可關閉的小部件:僅在點擊按鈕時關閉小部件

[英]Dismissible widget: dismiss widget only when tapping a button

我正在嘗試使用 dismissible 小部件僅在按下按鈕時才被解雇,而不是通過滑動。 有什么方法可以實現這一點,或者使用 Dismissible 小部件不可能做到這一點(或者我可能必須使用自定義動畫或類似的東西來實現我自己的小部件)?

關於如何實現這一目標的任何想法?

我嘗試將方向設置更改為 DismissDirection.none 以防止滑動。 那行得通,但是我不知道如何在按下按鈕時讓它消失。 我希望 Dismissible 會有某種 controller 參數,但它沒有。

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);
  
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Dismissible(
          key: UniqueKey(),
          direction: DismissDirection.none, // This prevents it from being swiped
          child: Container(
            width: 300.0,
            height: 100.0,
            color: Colors.blue,
          )
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {}, // I want this to somehow dismiss the Dismissible widget when this is pressed
      ),
    );
  }
}

(我在這里看到了一個類似的問題,但答案並沒有解決我的問題,因為我沒有嘗試實現一個出現在屏幕上的類似通知的小部件。我試圖關閉一個出現在我的應用程序的主體。)

Dismissible(
  key: ValueKey(id),
  background: Container(
    color: Theme.of(context).errorColor,
    child: Icon(
      Icons.delete,
      color: Colors.white,
      size: 40,
    ),
    alignment: Alignment.centerRight,
    padding: EdgeInsets.only(right: 20),
  ),
  direction: DismissDirection.endToStart,
  confirmDismiss: (direction) => showDialog(
    context: context,
    builder: ((context) => AlertDialog(
          title: Text('Are you sure?'),
          content: Text('Do you want to remove item from the cart'),
          actions: [
            TextButton(
                onPressed: () => Navigator.of(context).pop(false),
                child: Text('No')),
            TextButton(
                onPressed: () => Navigator.of(context).pop(true),
                child: Text('Yes'))
          ],
        )),
  ),
  onDismissed: (direction) {
    Provider.of<Cart>(context, listen: false).removeItem(productId);
  },
  child: Card(
    margin: EdgeInsets.symmetric(
      horizontal: 15,
      vertical: 4,
    ),
    child: Padding(
      padding: EdgeInsets.all(8),
      child: ListTile(
        leading: CircleAvatar(
            child: Padding(
                padding: EdgeInsets.all(5),
                child: FittedBox(child: Text('\$ $price')))),
        title: Text(title),
        subtitle: Text('Total: \$ ${(price * quantity)}'),
        trailing: Text('$quantity x'),
      ),
    ),
  ),
);



this might help, there's a on dismissed method which you need to apply,and inside the action list, you will get two button i.e yes or no, where you can perform your action.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM