user6274128
user6274128

Reputation:

Flutter prevent Snackbar from getting dismissed on swipe

Is there any way to prevent the Snackbar from dismissing when user swipes it down without making any modification in the source code of Snackbar class.

Upvotes: 10

Views: 6243

Answers (3)

ananthavel.s
ananthavel.s

Reputation: 81

we can use dismissDirection: DismissDirection.none

code snippet:

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: Builder(builder: (context) {
    return RaisedButton(
      onPressed: () => showSnackbar(context),
      child: Text("Show snackbar"),
    );
  }),
  );
}

void showSnackbar(context) {
  Scaffold.of(context)
      .showSnackBar(SnackBar(
        dismissDirection: DismissDirection.none,
        content: Text("I am here"),
        backgroundColor: Colors.blue,
      ))
  );
}

Upvotes: 8

Feu
Feu

Reputation: 5790

Placing a GestureDetector inside the SnackBar content and listening to onVerticalDragStart make it less dismissable, and using the extra \n\n\n makes it really annoying - but yet, dismissable. :)

In this example, it does prevent dismissing from the content area, but not from the SnackBar padding/margin area.

  void _showSnackBar(BuildContext context) {
    final snackbar = SnackBar(
      duration: Duration(days: 1),
      content: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onVerticalDragStart: (_) => debugPrint("no can do!"),
        child: Text("Hi! Don't try to dismiss me.\n\n\n"),
      )
    );

    Scaffold.of(context).showSnackBar(snackbar);
  }

SnackBar less dismissable

I even tried to simply place the SnackBar widget directly into the Scaffold's bottomsheet - however the results were the same, even wrapping the GestureDetector around the SnackBar.

Upvotes: 5

CopsOnRoad
CopsOnRoad

Reputation: 268544

You can try this.

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: Builder(builder: (context) {
    return RaisedButton(
      onPressed: () => showSnackbar(context),
      child: Text("Show snackbar"),
    );
  }),
  );
}

void showSnackbar(context) {
  Scaffold.of(context)
      .showSnackBar(SnackBar(
        content: Text("I am here"),
        backgroundColor: Colors.blue,
      ))
      .closed
      .then((reason) {
       if (reason == SnackBarClosedReason.swipe)
         showSnackbar(context);
  });
}

Upvotes: 2

Related Questions