Search code examples
flutterdartmaterialpageroute

Use Navigator.push (MaterialPageRoute) in a class method


I'm building an app using Flutter to play music.

I created a Class called MusicService with all the music functionalities implemented in methods like playMusic, seekMusic, onAudioComplete and so on.

I have my TrackScreen that is built based on the track (with the background of the track, the description and so on). In the init method of the screen I call an istance of MusicService to play music on the screen. So far so good.

What I would like to do is to build a new screen when a track is completed. This screen should be based on the next track in the playlist. The solution that I thougth is to call Navigator.Push in the onAudioComplete method of the class MusicService. The problem is that Navigator.Push requires a context and I don't know how specify it to refer to the context where it is called, i.e. the TrackScreen context.

Do you have any idea to solve this problem? Am I misunderstanding something?

Thank you for the help


Solution

  • You can navigate without context by using the navigatorKey of your MaterialApp

    First, you have to declare a GlobalKey

    final GlobalKey<NavigatorState> navKey = GlobalKey<NavigatorState>();
    

    and use it in your MaterialApp widget

    child: MaterialApp(
      navigatorKey: navKey,
      ...
    

    After you will be able to get it to push new screens

    navKey.currentState.push(...)