Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 .

like image 209
OverLoadedBurden Avatar asked Jul 25 '19 21:07

OverLoadedBurden


People also ask

How do I know if my snackbar is on Android?

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.

How many snack bars can be displayed at a time?

Frequency. Only one snackbar may be displayed at a time.

What is a snack bar notification?

Snackbars provide lightweight feedback about an operation. They show a brief message at the bottom of the screen on mobile and lower left on larger devices. Snackbars appear above all other elements on screen and only one can be displayed at a time.


1 Answers

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.

like image 155
Sukhi Avatar answered Sep 26 '22 16:09

Sukhi