flutter audio manager onEvents not working - flutter

I am using AudioManager and I am going to check audio status (start, ready, play, pause, volume and so on). Sometimes onEvents function doesn't work.
AudioManager audioManager = AudioManager.instance;
bool _isLoading;
try {
_isLoading = true;
String result = await audioManager.startInfo(audio, auto: true);
print("start result $result");
audioManager.nextMode(playMode: PlayMode.single);
} catch (e) {
print(e);
}
audioManager.onEvents((events, args) {
print("$events, $args");
switch (events) {
case AudioManagerEvents.start:
_isLoading = true;
break;
case AudioManagerEvents.ready:
_isLoading = false;
break;
case AudioManagerEvents.seekComplete:
print("seek completed");
break;
case AudioManagerEvents.buffering:
_isLoading = false;
break;
case AudioManagerEvents.playstatus:
_isLoading = false;
break;
case AudioManagerEvents.timeupdate:
_isLoading = false;
audioManager.updateLrc(args["position"].toString());
break;
case AudioManagerEvents.error:
_isLoading = false;
break;
case AudioManagerEvents.ended:
audioManager.next();
break;
case AudioManagerEvents.volumeChange:
_volume = audioManager.volume;
break;
default:
_isLoading = false;
break;
}
setState(() {});
});
_isLoading is always true even if audio is playing now.

Related

how to run a stream in different thread in dart

Future<bool> checkConnection() async {
var connectivityResult = await (Connectivity().checkConnectivity());
bool connOk = false;
if (connectivityResult == ConnectivityResult.mobile) {
bool ii = await checkConnectionWithUrl();
if (ii == true) {
connOk = true;
}
} else if (connectivityResult == ConnectivityResult.wifi) {
bool ii = await checkConnectionWithUrl();
if (ii == true) {
connOk = true;
}
} else if (connectivityResult == ConnectivityResult.ethernet) {
bool ii = await checkConnectionWithUrl();
if (ii == true) {
connOk = true;
}
} else if (connectivityResult == ConnectivityResult.bluetooth) {
bool ii = await checkConnectionWithUrl();
if (ii == true) {
connOk = true;
}
} else {
connOk = false;
}
return connOk;
}
Future<bool> checkConnectionWithUrl() async {
bool response = false;
while (true) {
var checkin = await client.get(Uri.https('www.google.com', '/'));
if (checkin.statusCode == 200) {
response = true;
break;
} else {
sleep(const Duration(milliseconds: 500));
}
}
return response;
}
Stream checkStream() async* {
dynamic result = false;
while (true) {
try {
result = await checkConnection();
} catch (error) {
result = false;
} finally {
yield result;
}
await Future.delayed(const Duration(seconds: 1));
}
}
I am making a app. And I want to learn multi threading in dart. The above function what it will do is it look for wifi state every second and update the Ui. But when I run the function it will drop frams in ui. So I what to run it in a diffrent thread. can i do it.
---My main goal ---
I want to run this function in a different thread how do I do it

Failed assertion: line 4397 pos 12: '_lifecycleState != _ElementLifecycle.defunct': is not true

im getting this error
When using this code in initstate
VideoPlayerController videoPlayerController;
bool stopvideo = false;
#override
void initState() {
super.initState();
videoPlayerController = VideoPlayerController.file(
widget.videourl,
)..initialize().then((value) {
videoPlayerController?.pause();
setState(() {
stopvideo = true;
});
videoPlayerController.setVolume(1);
videoPlayerController?.addListener(() {
if (videoPlayerController?.value != null) {
if (videoPlayerController.value?.duration ==
videoPlayerController.value?.position) {
if (this.mounted) {
setState(() {
stopvideo = true;
});
}
}
if (videoPlayerController.value.hasError) {
setState(() {
stopvideo = true;
});
}
}
});
});
}
The error happens because of this lines
videoPlayerController?.addListener(() {
if (videoPlayerController?.value != null) {
if (videoPlayerController.value?.duration ==
videoPlayerController.value?.position) {
if (this.mounted) {
setState(() {
stopvideo = true;
});
}
}
And I really have no idea why
Dispose looks like that
#override
void dispose() {
videoPlayerController?.pause();
videoPlayerController.removeListener(() {});
videoPlayerController?.dispose();
super.dispose();
}
I tried already removing the ? and a lot of other things but I cannot figure out what happened here .
Hope anyone can help .

Want to post geolocation on a external api using getx

I have already got the geolocation with longitude and latitude using the geolocation plugin with getx but now I want to post the same longitude and latitude on API with already present in the backhand the model is yet to be created and even the provider is also yet to be done and I don't know how and the location API post should run in the background once with the application opens up.
API body:-
{
"longitude":"55.5852",
"latitude":"77.6532"
}
Controller code:-
class RootController extends GetxController {
var latitude = 'Getting Latitude..'.obs;
var longitude = 'Getting Longitude..'.obs;
var address = 'Getting Address..'.obs;
final currentIndex = 0.obs;
final notificationsCount = 0.obs;
final customPages = <CustomPage>[].obs;
NotificationRepository _notificationRepository;
CustomPageRepository _customPageRepository;
StreamSubscription<Position> streamSubscription;
RootController() {
_notificationRepository = new NotificationRepository();
_customPageRepository = new CustomPageRepository();
}
#override
void onInit() async {
await getCustomPages();
getNotificationsCount();
if (Get.arguments != null && Get.arguments is int) {
changePageInRoot(Get.arguments as int);
} else {
changePageInRoot(0);
}
super.onInit();
getLocation();
}
#override
void onReady(){
super.onReady();
}
#override
void onClose(){
streamSubscription.cancel();
}
getLocation() async{
bool serviceEnabled;
LocationPermission permission;
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if(!serviceEnabled){
await Geolocator.openLocationSettings();
return Future.error('Location Services are disabled.');
}
permission = await Geolocator.checkPermission();
if(permission == LocationPermission.denied){
permission = await Geolocator.requestPermission();
if(permission == LocationPermission.denied){
return Future.error('Location permissions are denied');
}
}
if (permission == LocationPermission.deniedForever){
return Future.error('Location permissions are permanently denied');
}
streamSubscription = Geolocator.getPositionStream().listen((Position position) {
latitude.value = 'Latitude:${position.latitude}';
longitude.value = 'Longitude:${position.latitude}';
getAddressFromLatLang(position);
print(latitude.value);
print(longitude.value);
});
}
Future<void> getAddressFromLatLang(Position position)async{
List<Placemark> placemark = await
placemarkFromCoordinates(position.latitude,position.longitude);
Placemark place = placemark[0];
address.value = 'address:${place.locality},${place.country}';
}
List<Widget> pages = [
HomeView(),
// EServicesView2(),
ReviewsView(),
MessagesView(),
AccountView(),
];
Widget get currentPage => pages[currentIndex.value];
/**
* change page in route
* */
void changePageInRoot(int _index) {
currentIndex.value = _index;
}
void changePageOutRoot(int _index) {
currentIndex.value = _index;
Get.offNamedUntil(Routes.ROOT, (Route route) {
if (route.settings.name == Routes.ROOT) {
return true;
}
return false;
}, arguments: _index);
}
Future<void> changePage(int _index) async {
if (Get.currentRoute == Routes.ROOT) {
changePageInRoot(_index);
} else {
changePageOutRoot(_index);
}
await refreshPage(_index);
}
Future<void> refreshPage(int _index) async {
switch (_index) {
case 0:
{
await Get.find<HomeController>().refreshHome();
break;
}
case 2:
{
await Get.find<MessagesController>().refreshMessages();
break;
}
}
}
void getNotificationsCount() async {
notificationsCount.value = await _notificationRepository.getCount();
}
Future<void> getCustomPages() async {
customPages.assignAll(await _customPageRepository.all());
}
}
what else should I do?

i cannot stop/pause a song in audioplayers

I am using the audioplayers plugin in my code.
I can play audio but I cannot stop/pause audio. Following is a function that I use to play/stop the audio.
Future<void> onPlay({#required filepath, #required index}) async {
AudioPlayer audioPlayer = AudioPlayer(mode: PlayerMode.MEDIA_PLAYER);
if (!_isPlaying) {
int result = await audioPlayer.play(filepath, isLocal: true);
if (result == 1) {
setState(() {
_isPlaying = true;
_selectedIndex = index;
});
}
} else {
int result = await audioPlayer.stop();
if (result == 1) {
setState(() {
_isPlaying = false;
});
}
}
}
}
You're instantiating a new AudioPlayer audioPlayer object each time you call onPlay, which leaves you unable to stop that same player later.
Store your AudioPlayer audioPlayer in the state somewhere.
AudioPlayer audioPlayer = AudioPlayer(mode: PlayerMode.MEDIA_PLAYER);
Future<void> onPlay({#required filepath, #required index}) async {
if (!_isPlaying) {
int result = await audioPlayer.play(filepath, isLocal: true);
if (result == 1) {
setState(() {
_isPlaying = true;
_selectedIndex = index;
});
}
} else {
int result = await audioPlayer.stop();
if (result == 1) {
setState(() {
_isPlaying = false;
});
}
}
}

Flutter: Check Internet connectivity and navigate based on output?

I am new to flutter, I want to check whether the internet is available or not and based on the condition, the screen has to change. I have written the code below (screen switch is working properly), but I am not able to get bool output(internet). When I removed the Future in check internet class, it throws an error. Can you please solve the issue:
class _ScreenState extends State<ChannelScreen> {
bool isInternet;
bool result;
#override
void initState() {
// TODO: implement initState
result = check();
super.initState();
}
#override
Widget _buildChild() {
print ("The output “);
print (result);
if (result != Null && result == true) {
// if internet is ON
return Container();
}
//if internet is off
return Container();
}
Widget build(BuildContext context) {
return new Container(child: _buildChild());
}
}
Future<bool> check() async{
var connectivityResult = await Connectivity().checkConnectivity();
if (connectivityResult == ConnectivityResult.mobile) {
print ("******* Mobile is ON ******");
return true;
} else if (connectivityResult == ConnectivityResult.wifi) {
print ("******* Wifi is ON ******");
return true;
}
print ("No connectivity");
return false;
}
You can use StreamBuilder
StreamBuilder(
stream: Connectivity().onConnectivityChanged,
builder: (context, snapshot) {
// Use this to avoid null exception
if (snapshot.connectionState == ConnectionState.none) {
return CircularProgressIndicator();
} else {
ConnectivityResult result = snapshot.data;
// Check Connectivity result here and display your widgets
if(ConnectivityResult.none) {
yourWidgetForNoInternet();
} else {
yourWidgetForInternet();
}
}
},
)
bool hasInternet = false, isChecking = true;
#override
void initState() {
super.initState();
check();
}
#override
Widget build(BuildContext context) {
return Container(
child: isChecking
? ListTile(
leading: CircularProgressIndicator(), title: Text('Checking...'))
: hasInternet
? ListTile(title: Text('Your widget here...'))
: ListTile(
leading: Icon(Icons.info),
title: Text('No Internet Conncetion')));
}
check() async {
var connectivityResult = await Connectivity().checkConnectivity();
if (connectivityResult == ConnectivityResult.mobile) {
print("******* Mobile is ON ******");
setState(() {
isChecking = false;
hasInternet = true;
//navigate to another screen.....
});
} else if (connectivityResult == ConnectivityResult.wifi) {
print("******* Wifi is ON ******");
setState(() {
isChecking = false;
hasInternet = true;
//navigate to another screen.....
});
} else {
setState(() {
isChecking = false;
hasInternet = false;
});
}
}
There is a plugin to use connectivity:
https://pub.dev/packages/connectivity#-readme-tab-
I use following code to check whether the internet is connected or not
static Future<bool> checkInternetConnectivity() async {
bool isConnected;
try {
final result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
isConnected = true;
}
} on SocketException catch (_) {
isConnected = false;
}
return isConnected;
}