0

I'm trying to show a snackbar message once the user presses the "add to cart" button, but I get the following error:

[VERBOSE-2:ui_dart_state.cc(166)] Unhandled Exception: NoSuchMethodError: The method 'showSnackBar' was called on null.

Receiver: null

Tried calling: showSnackBar(Instance of 'SnackBar')

Here's my Code:

class ProductDetail extends StatefulWidget {
  final Product product;
  ProductDetail(this.product);
  @override
  _ProductDetailState createState() => _ProductDetailState();
}

class _ProductDetailState extends State<ProductDetail> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  CartService _cartService = CartService();

  _addToCart(BuildContext context, Product product) async {
    var result = await _cartService.addToCart(product);
    if (result > 0) {
      print(result);
      _showSnackMessage(Text(
        'Item added to cart successfully!',
        style: TextStyle(color: Colors.green),
      ));
    } else {
      _showSnackMessage(Text(
        'Failed to add to cart!',
        style: TextStyle(color: Colors.red),
      ));
    }
  }

  _showSnackMessage(message) {
    var snackBar = SnackBar(
      content: message,
    );
    _scaffoldKey.currentState.showSnackBar(snackBar);
  }

Can anyone please help me with your expertise?

Community
  • 1
  • 1
  • you already got the answer, but if you want to display a more beautiful and more customizable snackbar and without worrying about scaffold context, you can use this [package](https://pub.dev/packages/flushbar). – hewa jalal May 24 '20 at 18:33
  • hey @hiwajalal i really like that package! thanks for sharing it man! – Samuel Servin May 25 '20 at 20:05

1 Answers1

1

You have to add the _scaffoldKey to your Scaffold Widget as:

Scaffold(key:_scaffoldKey,...)

This will be null if you wont provide the key to your scaffold widget.

Adnan karim
  • 1,009
  • 10
  • 15