user6274128
user6274128

Reputation:

Flutter Snackbar dismiss listener

I was looking for a way to check if the Snackbar has been dismissed, either by the user or by the timeout stuff. I could't really get any listener of doing it.

This is what I got so far,

Scaffold.of(context)
    .showSnackBar(SnackBar(content: Text("Title")))
    .closed
    .then((reason) {
  // snackbar is now closed
});

This is the one way around, I was looking for exact listener. I don't want any work around, like setting duration of Snackbar and then listening to it after the duration has passed.

Upvotes: 20

Views: 9562

Answers (2)

Kalpesh Khandla
Kalpesh Khandla

Reputation: 746

Try with below code snippet

ScaffoldMessenger.of(context).hideCurrentSnackBar();

Upvotes: 0

user14631430
user14631430

Reputation:

see full example below I just wrapped SnackBar content with WillPopoScope and if the user pressed back button it will remove snackbar.
By default it will specify SnackBarClosedReason.remove reason

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(),
        body: FirstPage(),
      ),
    );
  }
}

class FirstPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: ElevatedButton(
        child: Text('go to test page'),
        onPressed: () => Navigator.of(context).push(MaterialPageRoute(builder: (context) => Test())),
      ),
    );
  }
}

class Test extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(
          child: Text('show snack'),
          onPressed: () => _showSnack(context),
        ),
      ),
    );
  }

  void _showSnack(BuildContext context) {
    ScaffoldMessenger.of(context)
        .showSnackBar(
          SnackBar(
            content: WillPopScope(
              onWillPop: () async {
                ScaffoldMessenger.of(context).removeCurrentSnackBar();
                return true;
              },
              child: Text("Title"),
            ),
          ),
        )
        .closed
        .then((reason) {
      print('------------ $reason');
    });
  }
}

Upvotes: 10

Related Questions