Magento – Magento 2 : Fatal error: Uncaught Error: Call to a member function dispatch()

magento2

I get this error in a block that I am developing to get current category. any ideas?

class CurrentCategory extends \Magento\Framework\View\Element\Template
{

protected $_registry;

public function __construct(
    \Magento\Framework\Registry $registry
)
{
    $this->_registry = $registry;
}

public function getCurrentCategory()
{
    return $this->_registry->registry('current_category');
}

PHP Fatal error: Uncaught Error: Call to a member function dispatch() on
null in
/vendor/magento/framework/View/Element/AbstractBlock.php:652

Best Answer

Try below code

class CurrentCategory extends \Magento\Framework\View\Element\Template
{

protected $_registry;

public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    \Magento\Framework\Registry $registry
)
{
    parent::__construct($context);
    $this->_registry = $registry;
}

public function getCurrentCategory()
{
    return $this->_registry->registry('current_category');
}

run upgrade, compile and deploy command and clear cache