我有一个滑块,它使用一个值来渲染自己,它在我按下按钮后开始渲染,但第一次渲染时,它会给我一个错误,然后开始正常工作。这就是错误:
在null上调用了getter"inSeconds"。接收方:空尝试调用:inSeconds
这是使用数据的小部件:
child: Consumer<MyAudio>(
builder: (context, audioPlayer, child) =>
SleekCircularSlider(
appearance: CircularSliderAppearance(
customWidths: CustomSliderWidths(
progressBarWidth: 2.0,
trackWidth: 1.0,
handlerSize: 1.0,
shadowWidth: 1.0,
),
infoProperties: InfoProperties(
modifier: (value) => '',
),
customColors: CustomSliderColors(
trackColor: Colors.grey,
progressBarColor: Colors.black,
),
size: 4.0,
angleRange: 360,
startAngle: -90.0,
),
min: 0.0,
max: audioPlayer.songLength.inSeconds.toDouble(),
initialValue:
audioPlayer.position.inSeconds.toDouble(),
),
),
),
这是一个函数,它给了我歌曲长度和位置的值:
class MyAudio extends ChangeNotifier {
Duration songLength;
Duration position;
AudioPlayer _player = AudioPlayer();
AudioCache cache;
MyAudio() {
initAudio();
}
initAudio() {
cache = AudioCache(fixedPlayer: _player);
_player.onDurationChanged.listen((Duration d) {
songLength = d;
notifyListeners();
});
_player.onAudioPositionChanged.listen((Duration p) {
position = p;
notifyListeners();
});
我想我应该使用异步函数,你觉得怎么样?如果你需要更多的代码,这里是我的github repo和所有文件:https://github.com/astroxd/sputofy_mobile/tree/main/sputofy_2滑块在/lib/miniPlayer
中,值在/lib/model/audioPlayer
中
问题是,当第一次构建小部件时,尽管audioPlayer
不是null,但audioPlayer.songLength
和audioPlayer.position
是null
。
在这段代码中,您定义了一对监听器,但回调是在第一次构建之后调用的。
_player.onDurationChanged.listen((Duration d) {
songLength = d;
notifyListeners();
});
_player.onAudioPositionChanged.listen((Duration p) {
position = p;
notifyListeners();
});
然后,解决方案可以是:
child: Consumer<MyAudio>(
builder: (context, audioPlayer, child) => SleekCircularSlider(
appearance: CircularSliderAppearance(
customWidths: CustomSliderWidths(
progressBarWidth: 2.0,
trackWidth: 1.0,
handlerSize: 1.0,
shadowWidth: 1.0,
),
infoProperties: InfoProperties(
modifier: (value) => '',
),
customColors: CustomSliderColors(
trackColor: Colors.grey,
progressBarColor: Colors.black,
),
size: 4.0,
angleRange: 360,
startAngle: -90.0,
),
min: 0.0,
max: audioPlayer.songLength?.inSeconds?.toDouble() ?? 0.0,
initialValue: audioPlayer.position?.inSeconds?.toDouble() ?? 0.0,
),
)
或者可以使用加载器。