音频播放器颤振问题



我正在设计一个音频播放器,滑块不工作,音频继续播放,即使我按下暂停。我附上了代码和日志。

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:geolocator/geolocator.dart';
import 'package:image_picker/image_picker.dart';
import 'package:intl/intl.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/services.dart';
import 'package:video_player/video_player.dart';
import 'package:audioplayers/audioplayers.dart';

import '../login.dart';

import 'package:flutter/services.dart';
class bestPractises extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _bestPractises();
}
}
class _bestPractises extends State<bestPractises> {
VideoPlayerController _controller;
Future<void> _initializeVideoPlayerFuture;
AudioPlayer audioPlayer= new AudioPlayer();
Duration duration = new Duration();
Duration position = new Duration();
bool playing = false;


String Lat = "",
Lng = "";
List<DropdownMenuItem> primtopicsitems = [];
String slctprimtopics = "",slcttopics="";
List<ImageProductSaleModel> imageList = new List();
List<UImodel> bpListUIModel = new List();
List<UImodel> topicListUIModel = new List();
List<DropdownMenuItem> bestpractitems = [],topicitems=[];
File farmerImageFile;
String AudioBase64 = "";
String audioPath = "";
bool isRecord = false;
TextEditingController remarksController = new TextEditingController();
TextEditingController txtmesgController = new TextEditingController();
TextEditingController precadvicController = new TextEditingController();
File fileMedia;
MediaSource source;
String vedio64 = "";
void initState() {
super.initState();
print("inistate");
initvalues();
getLocation();
// _controller = VideoPlayerController.asset(dataSource);
//_initializeVideoPlayerFuture = _controller.initialize();
//_controller.setLooping(true);

// getClientData();
}
void dispose() {
//_controller.dispose();
super.dispose();
}

Future<void> initvalues() async {
List bpList = await db.RawQuery('select * from animalCatalog where catalog_code='140'');
print('bpList ' + bpList.toString());
bpListUIModel = new List();
bestpractitems.clear();
for (int i = 0; i < bpList.length; i++) {
String ptName = bpList[i]["property_value"].toString();
String ptCode = bpList[i]["DISP_SEQ"].toString();
var uimodel = new UImodel(ptName, ptCode);
bpListUIModel.add(uimodel);
setState(() {
bestpractitems.add(DropdownMenuItem(
child: Text(ptName),
value: ptCode,
));
});
}
List topicList = await db.RawQuery('select * from animalCatalog where catalog_code='140'');
print('topicList ' + topicList.toString());
topicListUIModel = new List();
topicitems.clear();
for (int i = 0; i < topicList.length; i++) {
String topicName = topicList[i]["property_value"].toString();
String topicCode = topicList[i]["DISP_SEQ"].toString();
var uimodel = new UImodel(topicName, topicCode);
topicListUIModel.add(uimodel);
setState(() {
topicitems.add(DropdownMenuItem(
child: Text(topicName),
value: topicCode,
));
});
}
}
Future<bool> _onBackPressed() {
return Alert(
context: context,
type: AlertType.warning,
title: "Cancel",
desc: "Are you sure want to cancel?",
buttons: [
DialogButton(
child: Text(
"Yes",
style: TextStyle(color: Colors.white, fontSize: 20),
),
onPressed: () {
Navigator.pop(context);
Navigator.pop(context);
},
width: 120,
),
DialogButton(
child: Text(
"No",
style: TextStyle(color: Colors.white, fontSize: 20),
),
onPressed: () {
Navigator.pop(context);
},
width: 120,
)
],
).show() ??
false;
}
void getLocation() async {
bool isLocationEnabled = await Geolocator.isLocationServiceEnabled();
if (isLocationEnabled) {
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high);
print("latitude :" +
position.latitude.toString() +
" longitude: " +
position.longitude.toString());
setState(() {
Lat = position.latitude.toString();
Lng = position.longitude.toString();
});
} else {
Alert(
context: context,
title: "Information",
desc: "GPS Location not enabled",
buttons: [
DialogButton(
child: Text(
"OK",
style: TextStyle(color: Colors.white, fontSize: 18),
),
onPressed: () {
Navigator.pop(context);
Navigator.pop(context);
},
color: Colors.green,
)
]).show();
}
}
Widget build(BuildContext context) {
return SafeArea(
child: WillPopScope(
onWillPop: _onBackPressed,
child: Scaffold(
resizeToAvoidBottomInset: false,
appBar: AppBar(
centerTitle: true,
leading: IconButton(
icon: Icon(Icons.arrow_back, color: Colors.white),
onPressed: () {
_onBackPressed();
}),
title: Text(
'Best Practices',
style: new TextStyle(
color: Colors.white,
fontSize: 18.0,
fontWeight: FontWeight.w700),
),
iconTheme: IconThemeData(color: Colors.white),
backgroundColor: Colors.green,
brightness: Brightness.light,
),
body: Container(
child: Column(children: <Widget>[
Expanded(
child: ListView(
padding: EdgeInsets.all(10.0),
children: _getbpListings(
context), // <<<<< Note this change for the return type
),
flex: 8,
),
])),
),
),
);
}
List<Widget> _getbpListings(BuildContext context) {
List listings = List<Widget>();
listings.add(txt_label(
"Primary Topic", Colors.black, 16.0, false));
listings.add(singlesearchDropdown(
itemlist: bestpractitems,
selecteditem: slctprimtopics,
hint: "Select the Primary Topic",
onChanged: (value) {
setState(() {
slctprimtopics = value;
});
}));
listings.add(txt_label(
"Topic", Colors.black, 16.0, false));
listings.add(singlesearchDropdown(
itemlist: topicitems,
selecteditem: slcttopics,
hint: "Select the Topic",
onChanged: (value) {
setState(() {
slcttopics = value;
});
}));
// listings.add(txt_label(
//     "nText Messages  ", Colors.black, 16.0, false));
listings.add(Row(
children: <Widget>[
Expanded(
child: Row(
children: <Widget>[
Expanded(
flex: 3,
child: txt_label(
"nText Messages  ", Colors.black, 16.0, false)
//),
),
Expanded(
flex: 4,
child: txt_label(
"nBuyer 1  ", Colors.black, 16.0, false)
),
],
),
),
],
),
);
// listings
//     .add(txtfield_dynamic("", txtmesgController, true));
listings.add(Row(
children: <Widget>[
Expanded(
child: Row(
children: <Widget>[
Expanded(
flex: 3,
child: txt_label(
"nPrecautionary n Advices  ", Colors.black, 16.0, false)
//),
),
Expanded(
flex: 4,
child: txt_label(
"n This is the Advisory Message  ", Colors.black, 16.0, false)
),
],
),
),
],
),
);
// listings.add(txt_label(
//     "Precautionary Advices", Colors.black, 16.0, false));
//
// listings
//     .add(txtfield_dynamic("", precadvicController, true));
listings.add(Row(
children: <Widget>[
Expanded(
child: Row(
children: <Widget>[
Expanded(
flex: 3,
child: txt_label(
"nManuals  ", Colors.black, 16.0, false)
//),
),
Expanded(
flex: 4,
child: txt_label(
"n This is the Advisory Message  ", Colors.black, 16.0, false)
),
],
),
),
],
),
);
// listings.add(txt_label(
//     "Manuals          ", Colors.black, 16.0, false));
//
// listings
//     .add(txtfield_dynamic("", precadvicController, true));

listings.add(txt_label("nPhotos of the Advices", Colors.black, 16.0, false));
listings.add( Row(
children: [
Image(
image: AssetImage('images/1.jpg'),
height: 375,
width: 375,
),

const SizedBox(height: 24),

],
),
);

/*  listings.add( Row(
FutureBuilder (
future: _initializeVideoPlayerFuture,
builder: (context,snapshot)
{
if(snapshot.connectionState == ConnectionState.done)
{
return AspectRatio(aspectRatio: _controller.value.aspectRatio,
child: VideoPlayer(_controller),
);
}else {
return Center(
child : CircularProgressIndicator(),
);
}
},
),
floatingActionButton: FloatingActionButton(
onpressed : (){
setState(() {
if(_controller.value.isPlaying) {
_controller.pause();
} else {
_controller.play();
}
});
}
child:
Icon(_controller.value.isPlaying ? Icons.pause : Icons.play_arrow),
),
),
); */
// listings.add(img_picker(
//     label: "Photos of the Advices *",
//     onPressed: () {
//       getImage();
//     },
//     filename: farmerImageFile,
//     ondelete: () {
//       ondelete();
//     }));

listings.add(txt_label("Video", Colors.black, 16.0, false));
listings.add( Row(
children: [
RaisedButton(
child: Text('Video'),
onPressed: () => capture(MediaSource.video),
color: Colors.green,
textColor: Colors.white,
),
const SizedBox(height: 24),
Expanded(
child: fileMedia == null
? Container()
: (source == MediaSource.video
? Column(
children: [
VideoWidget(fileMedia),
],
)
: Container()),
),

],
),
);
listings.add(txt_label("nAudio", Colors.black, 16.0, false));
listings.add(Container(
color: Colors.white,
child: Column(
children: <Widget> [
//Image(image: AssetImage(''),),
slider(),
InkWell(
onTap: () {
getAudio();
},
child:Icon(
playing == false
? Icons.play_circle_outline
: Icons.pause_circle_outline,
size: 50,
color: Colors.blue,
),
)
],
),
),
);
listings.add(btn_dynamic(
label: "Audio",
bgcolor: Colors.green,
txtcolor: Colors.white,
fontsize: 18.0,
centerRight: Alignment.centerLeft,
margin: 10.0,
btnSubmit: () async {
audioPath = await Navigator.push(context,
MaterialPageRoute(builder: (context) => AudioRecorder()));
File audioFile = new File(audioPath);
List<int> fileBytes = await audioFile.readAsBytes();
AudioBase64 = base64Encode(fileBytes);
setState(() {
isRecord = true;
});
}));
if (isRecord) {
listings.add(Container(
color: Colors.blueGrey,
height: 40,
child: Center(
child: Row(
children: [
Expanded(
child: Center(
child: txt_label(
audioPath.split('/').last, Colors.white, 14.0, false)),
flex: 3,
),
Expanded(
child: InkWell(
onTap: () {
setState(() {
isRecord = false;
});
},
child: Icon(Icons.delete, color: Colors.red)),
flex: 1,
)
],
),
),
));
}
listings.add(txt_label("nRemarks", Colors.black, 14.0, false));
listings.add(txtfield_dynamic("Remarks", remarksController, true));
/* listings.add(Container(
child: Row(
children: [
Expanded(
flex: 1,
child: Container(
padding: EdgeInsets.all(3),
child: RaisedButton(
child: Text(
'Cancel',
style: new TextStyle(color: Colors.white, fontSize: 18),
),
onPressed: () {
_onBackPressed();
},
color: Colors.red,
),
),
),
Expanded(
flex: 1,
child: Container(
padding: EdgeInsets.all(3),
child: RaisedButton(
child: Text(
'Submit',
style: new TextStyle(color: Colors.white, fontSize: 18),
),
onPressed: () {
_bestpractisessubmit();
},
color: Colors.green,
),
),
),
//
],
),
)); */
return listings;
}
Widget slider() {
return Slider.adaptive(
min:  0.0,
value: position.inSeconds.toDouble(),
max: duration.inSeconds.toDouble(),
onChanged : (double value) {
setState(() {
audioPlayer.seek(new Duration(seconds: value.toInt()));
});
}
);
}
void getAudio() async {
var url = "https://www.learningcontainer.com/wp-content/uploads/2020/02/Kalimba.mp3";
if (playing) {
var res = await audioPlayer.pause();
if(res == 1) {
setState(() {
playing = false;
});
}
} else {
var res = await audioPlayer.play(url,isLocal: true);
if(res == 1) {
setState(() {
playing = true;
});
}
}
audioPlayer.onDurationChanged.listen((Duration dd) {
setState(() {
duration = dd;
});
});
audioPlayer.onAudioPositionChanged.listen((Duration dd) {
setState(() {
position = dd;
});
});
}
void _bestpractisessubmit() async{
if (slctprimtopics == "") {
errordialog(context, "Information",
"Primary Topic should not be empty");
}else if (slcttopics == ''){
errordialog(context, "Information",
"Topic should not be empty");
}else{
Alert(
context: context,
type: AlertType.info,
title: "Information",
desc: "Are you sure want to proceed?",
buttons: [
DialogButton(
child: Text(
"Yes",
style: TextStyle(color: Colors.white, fontSize: 20),
),
onPressed: () {

Navigator.pop(context);
Navigator.pop(context);
Navigator.pop(context);
},
width: 120,
),
DialogButton(
child: Text(
"No",
style: TextStyle(color: Colors.white, fontSize: 20),
),
onPressed: () {
Navigator.pop(context);
},
width: 120,
)
],
).show() ??
false;
}
}
Future getImage() async {
var image = await ImagePicker.platform
.pickImage(source: ImageSource.camera, imageQuality: 30);
setState(() {
farmerImageFile = new File(image.path);
});
}
void ondelete() {
setState(() {
if (farmerImageFile != null) {
setState(() {
farmerImageFile = null;
});
}
});
}
Future capture(MediaSource source) async {
setState(() {
this.source = source;
this.fileMedia = null;
});
final result = await Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => SourcePage(),
settings: RouteSettings(
arguments: source,
),
),
);
if (result == null) {
return;
} else {
setState(() {
fileMedia = result;
});
}
}
}

日志:

[ERROR:flutter/lib/ui/ui_dart_state.cc(199)]未处理的异常:setState()在dispose()之后调用:_bestpractices# e42c5(生命周期状态:未运行,未挂载)如果您对不再出现在小部件树中的小部件(例如,其父部件)的State对象调用setState(),则会发生此错误Widget不再在其构建中包含该Widget)。这个错误可以发生在代码从计时器或动画调用setState()时回调。首选的解决方案是在dispose()回调中取消计时器或停止侦听动画。另一个解决办法是检查"mounted"在调用setState()来获取该对象的属性确保对象仍在树中。如果由于另一个对象保留了对该状态的引用而调用setState(),则此错误可能表明存在内存泄漏对象从树中删除后。为了避免内存泄漏,考虑打破引用这个对象在处理()。# 0 State.setState。(包:颤振/src/widget/framework.dart: 1052:9)# 1的状态。设置状态(包:颤振/src/widget/framework.dart: 1087:6)# 2 _bestPractises.getAudio。(包:阿夫塔/屏幕/bestPractisesscreen.dart: 611:7)#3 _rootRunUnary (dart:async/zone.dart:1362:47)#4 _CustomZone.runUnary (dart:async/zone.dart:1265:19)#5 _customzone . rununary守卫(dart:async/zone.dart:1170:7)# 6 _BufferingStreamSubscription。_sendData(飞镖:异步/stream_impl.dart: 341:11)# 7 _DelayedData。执行(飞镖:异步/stream_impl.dart: 591:14)# 8 _StreamImplEvents。handleNext(飞镖:异步/stream_impl.dart: 706:11)# 9 _PendingEvents.schedule。(飞镖:异步/stream_impl.dart 663:7):#10 _roorun (dart:async/zone.dart:1346:47)#11 _CustomZone.run (dart:async/zone.dart:1258:19)#12 _customzone . run守卫(dart:async/zone.dart:1162:7)# 13 _CustomZone.bindCallbackGuarded。(飞镖:异步/zone.dart 1202:23):#14 _roorun (dart:async/zone.dart:1354:13)#15 _CustomZone.run (dart:async/zone.dart:1258:19)#16 _customzone . run守卫(dart:async/zone.dart:1162:7)# 17 _CustomZone.bindCallbackGuarded。(飞镖:异步/zone.dart 1202:23):#18 _microtaskLoop (dart:async/schedule_microtask.dart:40:21)#19 _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)

我有同样的问题,通过使用:

包装所有setState调用来解决:
if (mounted) {
setState(() {});
}

最新更新