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?