'How should I test for Navigator.pushNamed() in Flutter?

I have a test where I'm trying to observe the behaviour of the Navigator when the app navigates from page1.dart to page2.dart (push) and back (pop). Using verify from the Mockito package, I can successfully verify that the push behaviour works when I am not using pushNamed(). However, after I changed my project to use Named Route, I wasn't able to find a correct way to implement the mock and test the navigation.

Is there a proper way how to check, that Navigator was called? Or is there a recommended way to mock and replace the navigator?

Edit: I found a flutter library Mockingjay to Mock the Navigator.



Solution 1:[1]

You can define routes in your MaterialApp:

routes: {
    // When navigating to the "/" route, build the FirstScreen widget.
    '/': (context) => const FirstScreen(),
    // When navigating to the "/second" route, build the SecondScreen widget.
    '/second': (context) => const SecondScreen(),
  },

And then use Navigator to Push to your destination:

Navigator.pushNamed(context, '/second');

For more details check this flutter doc on Navigate with named routes.

Solution 2:[2]

OnPressed:() {
     Navigator.push( context,
       MaterialPageRoute(
         builder: (context) => NewScreen()
       )
      );
    },

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharman
Solution 2 Rush tomato