Meggy
Meggy

Reputation: 1681

Pass a String to a Class in Flutter?

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?

Upvotes: 3

Views: 1037

Answers (2)

Abbasihsn
Abbasihsn

Reputation: 2171

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.

Upvotes: 2

Abbasihsn
Abbasihsn

Reputation: 2171

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");

Upvotes: 1

Related Questions