Pass a String to a Class in Flutter?

154

Solution 1

replace

static const url = 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3';

  PageManager() {
    _init();
  }

with

String url; // don't use const variable!
PageManager({this.url="You can set a default URL here"}){
   _init();
}

now you can use it in your main.dart as follow:

_pageManager = PageManager(url: "YOUR URL");

let me know the result.

Solution 2

You can use a constructor. In PageManager class add this function:

String url;
PageManager(this.url);

then you can define an object related to this class as follow:
PageManager pageManager = new PageManager("YOUR URL");
Share:
154
Meggy
Author by

Meggy

I'm a self-taught novice stumbling like a drunk through php, javascript, mysql, drupal and flutter.

Updated on December 30, 2022

Comments

  • Meggy
    Meggy over 1 year

    I'm using the streaming_audio_flutter_demo project on Github. https://github.com/suragch/streaming_audio_flutter_demo

    This has a class that provides a ValueListenableBuilder and a slider along with play and pause controls for my app.

    The only problem is, I'd like to change the example URL to my own;

    static const url = 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3';
    

    But I'm not sure how to pass it to the class from the main page of my app. Here's the code for the PageManager class;

     class PageManager {
      final progressNotifier = ValueNotifier<ProgressBarState>(
        ProgressBarState(
          current: Duration.zero,
          buffered: Duration.zero,
          total: Duration.zero,
        ),
      );
      final buttonNotifier = ValueNotifier<ButtonState>(ButtonState.paused);
    
      late AudioPlayer _audioPlayer;
      static const url = 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3';
    
      PageManager() {
        _init();
      }
    
      void _init() async {
        // initialize the song
        _audioPlayer = AudioPlayer();
        await _audioPlayer.setUrl(url);        
      }  
    }
    

    The String I need to pass looks like this;

    _current?.path
    

    So how can I access the

    static const url = 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3';
    

    from the main page of my app?