Search code examples
fluttersnackbar

How to check if there is a snack bar showing?


I'm trying to get the current snack bar (showing one) to determine if it is the same snack that am trying to show or not ; in other words ,i don't want to duplicate the snack , but i couldn't get it.

I'v tried to google it up but nothing showed about it and what is really pissing me off is when i call Scaffold.of(context).showSnackBar(sb); multiple times they show will show one at a time until they end .

import 'package:flutter/material.dart';

const sb = SnackBar(
  content: Text('the snack bar'),
);
void main() => runApp(MaterialApp(
      title: 'Snack bar test',
      home: Scaffold(
        appBar: AppBar(
          title: Text('snack bar demo'),
        ),
        body: Center(
          child: MyApp(),
        ),
      ),
    ));

class MyApp extends StatelessWidget {
  const MyApp({Key key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return RaisedButton(
      child: Text('push to test'),
      onPressed: () {
        // Scaffold.of(context).
        Scaffold.of(context).showSnackBar(sb);
      },
    );
  }
}

What i want to achieve is something like this :-

if (sb.isShowing()){
  //hide or remove it
  }

and thanks in advance .


Solution

  • You can use .close() event. It specifies how a snack bar is closed. Details here and Sample code below :

       bool _isSnackbarActive = false ;
    
       ...
       ...
    
    
       _isSnackbarActive = true ;
    
       Scaffold.of(context)
           .showSnackBar(SnackBar(content: Text("Title")))
           .closed
           .then((SnackBarClosedReason reason) {
         // snackbar is now closed. 
           _isSnackbarActive = false ;
    
    });
    

    The variable _isSnackbarActive to true when snackBar is displayed and set it to false when it is closed. In your onPressed event, just check the status of the snackbar and decide if new snackbar is to be shown or not. In addition, per your requirement, you can check the text on the current snack bar to see if the intended snackbar and the current one are same.