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

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 .

Related

(No implementation found for method _init on channel plugins.flutter.io/google_mobile_ads)

couldnt find anything wrong with it
dependencies:
google_mobile_ads: ^1.1.0
Error:
MissingPluginException(No implementation found for method
MobileAds#initialize on channel plugins.flutter.io/google_mobile_ads)
at Object.throw_ [as throw] (http://localhost:58428/dart_sdk.js:5067:11)
at platform_channel.MethodChannel.new._invokeMethod (http://localhost:58428/packages/flutter/src/services/restoration.dart.lib.js:1560:21)
at _invokeMethod.next ()
at http://localhost:58428/dart_sdk.js:40571:33
at _RootZone.runUnary (http://localhost:58428/dart_sdk.js:40441:59)
at _FutureListener.thenAwait.handleValue (http://localhost:58428/dart_sdk.js:35363:29)
at handleValueCallback (http://localhost:58428/dart_sdk.js:35931:49)
at Function._propagateToListeners (http://localhost:58428/dart_sdk.js:35969:17)
at _Future.new.[_completeWithValue] (http://localhost:58428/dart_sdk.js:35817:23)
at async._AsyncCallbackEntry.new.callback (http://localhost:58428/dart_sdk.js:35838:35)
at Object._microtaskLoop (http://localhost:58428/dart_sdk.js:40708:13)
at _startMicrotaskLoop (http://localhost:58428/dart_sdk.js:40714:13)
at http://localhost:58428/dart_sdk.js:36191:9
AdsManager :
class AdsManager {
static bool testMode = true;
late InterstitialAd? interstitialAd;
int numInterstitialLoadAttempts = 0;
static String get rewardedAdUnitId {
if (testMode == true) {
return RewardedAd.testAdUnitId;
} else if (Platform.isAndroid) {
return "ca-app-pub-1571703103044065/4157175333";
} else if (Platform.isIOS) {
return "ca-app-pub-1571703103044065/4157175811";
} else {
throw UnsupportedError("Unsupported platform");
}
}
static String get bannerAdUnitId {
if (testMode == true) {
return BannerAd.testAdUnitId;
} else if (Platform.isAndroid) {
return "ca-app-pub-1571703103044065/4157175333";
} else if (Platform.isIOS) {
return "ca-app-pub-1571703103044065/6858117501";
} else {
throw UnsupportedError("Unsupported platform");
}
}
static String get interstitialAdUnitId {
if (testMode == true) {
return InterstitialAd.testAdUnitId;
} else if (Platform.isAndroid) {
return "ca-app-pub-1571703103044065/4157175333";
} else if (Platform.isIOS) {
return "ca-app-pub-1571703103044065/2885703588";
} else {
throw UnsupportedError("Unsupported platform");
}
}
}
in page.dart
class _HomePageState extends State<HomePage> {
late RewardedAd _rewardedAd;
late InterstitialAd interstitialAd;
int numInterstitialLoadAttempts = 0;
bool isRewardedAdReady = false;
var _balance = 0;
//Banner Ad
late BannerAd _bannerAd;
bool _adIsLoaded = false;
#override
void initState() {
_initGoogleMobileAds();
_loadRewardedAd();
loadInterstitialAd();
//
_bannerAd = BannerAd(
adUnitId: AdsManager.bannerAdUnitId,
request: const AdRequest(),
size: AdSize.banner,
listener: BannerAdListener(
onAdLoaded: (ad) {
setState(() => _adIsLoaded = true);
},
onAdFailedToLoad: (ad, error) {
setState(() => _adIsLoaded = false);
},
));
_bannerAd.load();
//
super.initState();
}
#override
void dispose() {
super.dispose();
}

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;
});
}
}
}

Calling SharedPreferences in didChangeDependencies

Can you call a boolean with Shared Preferences in didChangeDependencies?
I need to use isToolTipTapped as a conditional in my build method but it doesn't seem to be working..
#override
void didChangeDependencies() async {
isToolTipTapped = await checkIfToolTipTapped();
print('$isToolTipTapped');
super.didChangeDependencies();
}
Future<bool> checkIfToolTipTapped() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getBool(SchnapConfigValues.toolTipTapped ?? false);
}
print('$isToolTipTapped'); does return the boolean in didChangeDependencies method but my build method doesn't take the value
I think you should be try this code:
class _DemoPageState extends State<DemoPage> {
static const TAG = 'DemoPage';
bool isToolTipTapped;
Future<bool> checkIfToolTipTapped() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getBool(SchnapConfigValues.toolTipTapped ?? false);
}
#override
void didChangeDependencies() {
super.didChangeDependencies();
checkIfToolTipTapped().then((value) {
setState(() {
isToolTipTapped = value;
});
});
}
#override
Widget build(BuildContext context) {
if (isToolTipTapped == null) {
return Your Loading Widget...
} else {
//Handle logic with isToolTipTapped
}
}
}
class _DemoPageState extends State<DemoPage> {
static const TAG ='DemoPage';
bool isToolTipTapped = false;
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
Future<bool> checkIfToolTipTapped() async {
SharedPreferences prefs = await _prefs;
return prefs.getBool(SchnapConfigValues.toolTipTapped ?? false);
}
#override
void didChangeDependencies() {
super.didChangeDependencies();
checkIfToolTipTapped().then((value) {
setState(() {
isToolTipTapped = value;
});
});
}
#override Widget build(BuildContext context) {
if (isToolTipTapped) {
return Your Loading Widget...
} else {
//Handle logic with isToolTipTapped
}
}
}

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;
}