Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'showSnackBar' & 'hideCurrentSnackBar' is deprecated and shouldn't be used

Please help me out, _scaffoldKey and _scaffoldKey.currentState cuasing main problem while fixing the code.

I have following code:

void customSnackBar(GlobalKey<ScaffoldState> _scaffoldKey, String msg,
    {double height = 30, Color backgroundColor = Colors.black}) {
  if (_scaffoldKey == null || _scaffoldKey.currentState == null) {
    return;
  }
  _scaffoldKey.currentState.hideCurrentSnackBar();
  final snackBar = SnackBar(
    backgroundColor: backgroundColor,
    content: Text(
      msg,
      style: TextStyle(
        color: Colors.white,
      ),
    ),
  );
  _scaffoldKey.currentState.showSnackBar(snackBar);
}

I have gone through ScaffoldMessenger documentation but not able to understand how to convert above code to use ScaffoldMessenger?

like image 242
MURARI Yadav Avatar asked Nov 15 '25 07:11

MURARI Yadav


2 Answers

Yeah, you can now use ScaffoldMessenger instead. take a look here https://flutter.dev/docs/release/breaking-changes/scaffold-messenger Show it here :

ScaffoldMessenger.of(context).showSnackBar(SnackBar(
    content: const Text('snack'),
    duration: const Duration(seconds: 1),
    action: SnackBarAction(
      label: 'ACTION',
      onPressed: () {
          ScaffoldMessenger.of(context).hideCurrentSnackBar;
      },
    ),
  ));
like image 170
Dwi Kurnianto M Avatar answered Nov 17 '25 21:11

Dwi Kurnianto M


Change GlobalKey<ScaffoldState> to GlobalKey<ScaffoldMessengerState>.

like image 44
Kanan Avatar answered Nov 17 '25 20:11

Kanan