Flutter:将参数传递给Consumed class by Consumer

Flutter: Pass parameters to Consumed class by Consumer

我正在尝试在 Flutter 中构建一个音频播放器。我正在使用 audioplayers 包。

我有一个音频播放器 class,代码如下:

import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';

class MyAudio extends ChangeNotifier{

  Duration totalDuration;
  Duration position;
  String audioState;
  final String url;

  MyAudio(this.url){
    initAudio();
  }

  AudioPlayer audioPlayer = AudioPlayer();

  initAudio(){
    audioPlayer.onDurationChanged.listen((updatedDuration) {
        totalDuration = updatedDuration;
        notifyListeners();
    });

    audioPlayer.onAudioPositionChanged.listen((updatedPosition) {
        position = updatedPosition;
        notifyListeners();
    });

    audioPlayer.onPlayerStateChanged.listen((playerState) {
      if(playerState == AudioPlayerState.STOPPED)
        audioState = "Stopped";
      if(playerState==AudioPlayerState.PLAYING)
        audioState = "Playing";
      if(playerState == AudioPlayerState.PAUSED)
        audioState = "Paused";
      notifyListeners();
    });
  }

  playAudio(){
    audioPlayer.play(url);
  }

  pauseAudio(){
    audioPlayer.pause();
  }

  stopAudio(){
    audioPlayer.stop();
  }

  seekAudio(Duration durationToSeek){
    audioPlayer.seek(durationToSeek);
  }
}

如您所见,有一个名为 url 的参数,我想在从播放列表中挑选歌曲时传递该变量。但是,我使用这个播放器时 Consumer 比如:

Consumer<MyAudio>(
  builder:(_,myAudioModel,child) => Slider(...)

在这种情况下,我无法传递 URL 参数,我应该如何使用 Consumer 才能显式传递 URL 参数?

MyAudio 通知程序作为应用程序中的单个依赖项被安装。如果要更改当前 url,请在 play 方法中作为参数传递并调用:

class MyAudio extends ChangeNotifier{

  Duration totalDuration;
  Duration position;
  String audioState;

  MyAudio(){
    initAudio();
  }

  AudioPlayer audioPlayer = AudioPlayer();

  initAudio(){
    audioPlayer.onDurationChanged.listen((updatedDuration) {
        totalDuration = updatedDuration;
        notifyListeners();
    });

    audioPlayer.onAudioPositionChanged.listen((updatedPosition) {
        position = updatedPosition;
        notifyListeners();
    });

    audioPlayer.onPlayerStateChanged.listen((playerState) {
      if(playerState == AudioPlayerState.STOPPED)
        audioState = "Stopped";
      if(playerState==AudioPlayerState.PLAYING)
        audioState = "Playing";
      if(playerState == AudioPlayerState.PAUSED)
        audioState = "Paused";
      notifyListeners();
    });
  }

  playAudio(String url){
    audioPlayer.play(url);
  }

  pauseAudio(){
    audioPlayer.pause();
  }

  stopAudio(){
    audioPlayer.stop();
  }

  seekAudio(Duration durationToSeek){
    audioPlayer.seek(durationToSeek);
  }
}

在消费者中:

Consumer<MyAudio>(
  builder:(_,myAudioModel,child) {
    myAudioModel.play("MyUrl");
    return MyWidget();
  }),

或者,如果您有处理播放操作的回调:

```dart
Consumer<MyAudio>(
  builder:(_,myAudioModel,child) {
    return MyWidget(
      onPressed: () => myAudioModel.play("MyUrl"),
      // ...
    );
  }),