flutterdartargumentsflutter-onpressed

Parse arguments with Navigator.push shows error too many positional arguments: 0 expected, but 1 found


I want to parse arguments with Navigator.push() to my other dart file .

Because I want to send the path of the selected song in songlist, to the music player main UI (For Playing)

[ songlist.dart ]

child:ListView.builder(
                      itemCount: getSongList()[0].length,
                      itemBuilder: (BuildContext context, int index) {
                        return ListTile(
                          title: Text(getSongList()[1][index].split('/').last,style:
                          const TextStyle(
                              fontSize: 21
                          ),),
                          leading: IconButton(onPressed: (){
                            Navigator.push(context,MaterialPageRoute(builder: (context) => music_player()));
                          },
                              icon: Icon(Icons.my_library_music)),
                        );
                      }
                  )
              ),

[ musicplayer.dart ]

class music_player extends StatefulWidget {
  const music_player({Key? key}) : super(key: key);

  @override
  State<music_player> createState() => _music_playerState();
}

class _music_playerState extends State<music_player> {
  // codes
}

Just wanna know how to parse arguments from my first file to second file. If I pass arguments there will be an error :

too many positional arguments: 0 expected, but 1 found.

Thanks in advance.


Solution

  • you need to add parameter(selectedSongs) in widget like this:

    class MusicPlayer extends StatefulWidget {
      final selectedSongs;
    
      const MusicPlayer({
        Key? key,
        this.selectedSongs,
      }) : super(key: key);
    
      @override
      State<MusicPlayer> createState() => _MusicPlayerState();
    }
    
    class _MusicPlayerState extends State<MusicPlayer> {
      @override
      Widget build(BuildContext context) {
        return const Placeholder();
      }
    }
    

    this way you can use in Navigator.push:

    Navigator.push(context,MaterialPageRoute(builder: (context) => MusicPlayer(selectedSongs: selectedsongList,))));