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

Viewed 1110

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?

1 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;
      },
    ),
  ));
Related