NoSuchMethodError: The method 'showSnackBar' was called on null

NoSuchMethodError: The method 'showSnackBar' was called on null

我试图在用户按下“添加到购物车”按钮后显示一条快餐栏消息,但出现以下错误:

[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')

这是我的代码:

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);
  }

谁能用你的专业知识帮助我?

您必须将 _scaffoldKey 添加到您的 Scaffold 小部件中:

Scaffold(key:_scaffoldKey,...)

如果您不提供脚手架小部件的密钥,这将为 null。