构建无状态小部件时,我会使用以下代码按顺序播放一些声音:
#include <Rcpp.h>
// [[Rcpp::plugins(cpp11)]]
// [[Rcpp::export]]
Rcpp::NumericVector convertToDouble(Rcpp::StringVector x) {
// Numeirc vector to store results
std::vector<double> res;
// Double for converted values
double converted_double;
for(Rcpp::StringVector::iterator it = x.begin(); it != x.end(); ++it) {
// Get [] for vector element
int index = std::distance(x.begin(), it);
// Help the conversion to string
std::string temp = Rcpp::as<std::string>(x[index]);
// Convert
converted_double = std::stod(temp);
// Add to a std vector... Do not use with Rcpp types
res.push_back(converted_double);
}
// Convert and return the Rcpp type as desired.
return Rcpp::wrap(res);
}
当用户在结束播放声音之前关闭当前小部件时,即使使用以下代码关闭了当前路线,声音仍然起作用:
convertToDouble(c("2.3", "34.25a", "abc32def.43", "12", "1.5"))
# Error in convertToDouble(c("2.3", "34.25a", "abc32def.43", "12", "1.5")) : stod: no conversion
我的解决方法是使用一个布尔变量来指示关闭操作是否完成。
播放声音代码:
abc32def.43
关闭当前小部件:
await _audioPlayer.play(contentPath1, isLocal: true);
await Future.delayed(Duration(seconds: 4));
await _audioPlayer.play(contentPath2, isLocal: true);
await Future.delayed(Duration(seconds: 4));
await _audioPlayer.play(contentPath3, isLocal: true);
如果我的小部件关闭了,有没有更好的方法来停止异步方法?
答案 0 :(得分:3)
如果将窗口小部件更改为StatefulWidget,则可以具有如下功能:
void _playSounds() {
await _audioPlayer.play(contentPath1, isLocal: true);
await Future.delayed(Duration(seconds: 4));
if (!mounted) return;
await _audioPlayer.play(contentPath2, isLocal: true);
await Future.delayed(Duration(seconds: 4));
if (!mounted) return;
await _audioPlayer.play(contentPath3, isLocal: true);
}
,然后在dispose方法中处置播放器:
@override
void dispose() {
_audioPlayer?.dipose();
super.dispose();
}