Call to a member function addMessage() on null

Hello friends, I am trying to add slim flash message to be accessed with my controller
using Slim framework 3 & Twig, But I get error says :
Call to a member function addMessage() on null,
Buzz\Controllers\MailController::$flash in C:\xampp\htdocs\myapp\app\Controllers\MailController.php on line 63

// my bootfile.php

* <?php
*     $container['MailController'] = function($container){ return new \Buzz\Controllers\MailController($container); };                                                                                                                                         
*     $container['flash'] = function($container){   return new \Slim\Flash\Messages; };
*     $container['view'] = function($container){
*         $view = new \Slim\Views\Twig(__DIR__ . '/../resources/views', [  'cache' => false,
*         ]);
*         $view->addExtension(new \Slim\Views\TwigExtension( $container->router,  $container->request->getUri()  ));
*         $view->getEnvironment()->addGlobal('flash', $container->flash);
*         return $view;
*     };

// MailController.php

*  public function sendmail($request, $response){
*          $sent = mail->send();
*          if ($sent) { $this->flash->addMessage('mailsuccess', 'Thank you for contacting'); }
* }

Are you assigning the flash object ($this->flash) in your constructor? See lines 12 - 21 in this example:

Thank you. But what I have done is to regester the flash message instance, connecting it to view and accessing it throught my MaiController that extends the base controller as follows

namespace Buzz\Controllers;
class Controller {
    protected $container;
    public function __construct($container)
    {
        $this->container = $container;
    }
}

Then :
class MailController extends Controller {   }

Then to my boot file id did something like this
//Register flash messages
$container['flash'] = function($container){  return new \Slim\Flash\Messages; };
$container['view'] = function($container){
    $view = new \Slim\Views\Twig(__DIR__ . '/../resources/views', [ 'cache' => false, ]);
    $view->addExtension(new \Slim\Views\TwigExtension( $container->router, $container->request->getUri() ));
    $view->getEnvironment()->addGlobal('flash', $container->flash);
    return $view;
 };

In that case it looks like your flash object would be at $this->container->flash, so you might need something more like this:

if ($sent) { $this->container->flash->addMessage('mailsuccess', 'Thank you for contacting'); }

You may wish to read a little on service locator versus dependency injection.

Thank you, I did both ways. 1.Initializing Flash Message instance to my MailController and 2. calling the flesh Message class throught the container… But both returning NULL, I don’t understand why I can’t catch the message I passed to “addMessage()”. That was a big issue to me now. Please help me.