Video freezes when Admob's ad load Flutter - flutter

Hy there everyone. I'm new to Flutter. I want to implement Admob ads in my app. Basically my app is about live streaming of News.
Whenever the ads load the audio works fine but there is a lag in video.
Can anyone help me with this??
Hy there everyone. I'm new to Flutter. I want to implement Admob ads in my app. Basically my app is about live streaming of News.
Whenever the ads load the audio works fine but there is a lag in video.
Can anyone help me with this??
Hy there everyone. I'm new to Flutter. I want to implement Admob ads in my app. Basically my app is about live streaming of News.
Whenever the ads load the audio works fine but there is a lag in video.
Can anyone help me with this??
import 'package:better_player/better_player.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
class StreamPlayer extends StatefulWidget {
final String channelURL;
final String channelName;
final String channelImage;
StreamPlayer(
{#required this.channelURL,
#required this.channelName,
#required this.channelImage});
#override
_StreamPlayerState createState() => _StreamPlayerState();
}
class _StreamPlayerState extends State<StreamPlayer> {
BetterPlayerController _controller;
BannerAd _bannerAd;
bool _isBannerAdReady = false;
#override
void initState() {
super.initState();
playerConfig();
getBanner();
}
playerConfig() {
BetterPlayerDataSource betterPlayerDataSource = BetterPlayerDataSource(
BetterPlayerDataSourceType.network, widget.channelURL,
liveStream: true);
_controller = BetterPlayerController(
BetterPlayerConfiguration(
aspectRatio: 16 / 9,
autoDetectFullscreenDeviceOrientation: true,
autoPlay: true,
),
betterPlayerDataSource: betterPlayerDataSource);
}
getBanner() {
_bannerAd = BannerAd(
adUnitId: 'ca-app-pub-3940256099942544/6300978111', //Ad for Testing
request: AdRequest(),
size: AdSize.banner,
listener: AdListener(
onAdLoaded: (ad) {
setState(() {
_isBannerAdReady = true;
});
},
onAdFailedToLoad: (ad, err) {
print('Failed to load a banner ad: ${err.message}');
_isBannerAdReady = false;
ad.dispose();
},
),
);
return _bannerAd.load();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
backgroundColor: Colors.transparent,
elevation: 0,
title: Container(
width: 200,
height: 45,
decoration: BoxDecoration(
color: Colors.blueAccent.withOpacity(0.3),
borderRadius: BorderRadius.all(Radius.circular(30))),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CachedNetworkImage(
imageUrl: widget.channelImage,
width: 25,
height: 25,
fit: BoxFit.contain,
placeholder: (context, url) => Icon(
Icons.image,
size: 25,
),
errorWidget: (context, url, error) => Icon(
Icons.image,
size: 50,
)),
SizedBox(
width: 15,
),
Text(widget.channelName,
style: GoogleFonts.teko(
color: Theme.of(context).primaryColor == Colors.blue
? Colors.black54
: Colors.grey[50],
fontSize: 22,
fontWeight: FontWeight.w600,
)),
SizedBox(
width: 5,
),
],
),
)),
body: Container(
child: Column(
children: [
Center(
child: BetterPlayer(
controller: _controller,
),
),
_isBannerAdReady
? Container(
height: 100,
child: AdWidget(ad: _bannerAd),
)
: Container(),
],
),
),
);
}
}

I know its too late. Just posting here to give refernce to others.
As I have wasted lots of hours due to it.
I was also facing the same issue when I was using video player with google_mobile_ads ad library
So I just switch to native_admob_flutter ad library on video page.
And it is working fine.
Hope this will save some hours of others.

Related

_CastError (Null check operator used on a null value) while trying to play song

I am facing _CastError and I am unable to fix it. If anyone can correct the existing code and attach it, it would be much appreciated. I have used the ! operator and I think it's the main reason for this issue. I don't know how to handle this issue . A corrected code and attached would be much appreciated
Here is my Code: I am also attaching the error screenshot so please have a look.
_CastError ScreenShot
import 'package:ai_music_player/model/radio.dart';
import 'package:ai_music_player/utils/ai_utils.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:velocity_x/velocity_x.dart';
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List<MyRadio>? radios;
MyRadio? _selectedRadio;
Color? _selectedColor;
bool _isPlaying = false;
final AudioPlayer _audioPlayer = AudioPlayer();
#override
void initState() {
super.initState();
fetchRadios();
_audioPlayer.onPlayerStateChanged.listen((event) {
if (event == PlayerState.PLAYING) {
_isPlaying = true;
} else {
_isPlaying = false;
}
setState(() {});
});
}
fetchRadios() async {
final radioJson = await rootBundle.loadString("assets/radio.json");
radios = MyRadioList.fromJson(radioJson).radios;
setState(() {});
}
playMusic(String url) {
_audioPlayer.play(url);
_selectedRadio = radios!.firstWhere((element) => element.url == url);
print(_selectedRadio!.name);
setState(() {});
}
#override
Widget build(BuildContext context) {
return Scaffold(
drawer: Drawer(),
body: Stack(
children: [
VxAnimatedBox()
.size(context.screenWidth, context.screenHeight)
.withGradient(
LinearGradient(
colors: [AIColors.primaryColor1, AIColors.primaryColor2],
begin: Alignment.topLeft,
end: Alignment.bottomRight),
)
.make(),
AppBar(
title: "AI Player".text.xl4.bold.white.make().shimmer(
primaryColor: Vx.purple300, secondaryColor: Colors.white),
backgroundColor: Colors.transparent,
elevation: 0.0,
centerTitle: true,
).h(120),
radios != null
? VxSwiper.builder(
itemCount: radios!.length,
enlargeCenterPage: true,
itemBuilder: (context, index) {
final rad = radios![index];
return VxBox(
child: ZStack(
[
Positioned(
top: 0,
right: 0,
child: VxBox(
child: rad.lang.text.uppercase.bold.white
.make()
.px16(),
)
.height(40)
.black
.alignCenter
.withRounded(value: 10)
.make(),
),
Align(
alignment: Alignment.bottomCenter,
child: VStack(
[
rad.name.text.xl5.white.bold.make(),
5.heightBox,
rad.tagline.text.xl.white.bold.italic.make(),
],
crossAlignment: CrossAxisAlignment.center,
),
),
Align(
alignment: Alignment.center,
child: [
const Icon(
CupertinoIcons.play_circle,
color: Colors.white54,
size: 60,
),
10.heightBox,
"DOUBLE TAB TO PLAY".text.gray300.make()
].vStack(),
),
],
),
)
.clip(Clip.antiAlias)
.bgImage(
DecorationImage(
image: NetworkImage(rad.image),
fit: BoxFit.cover,
colorFilter: ColorFilter.mode(
Colors.black.withOpacity(0.3),
BlendMode.darken),
),
)
.border(color: Colors.black, width: 3)
.withRounded(value: 60.0)
.make()
.onInkDoubleTap(() {
_audioPlayer.play(rad.url);
});
},
aspectRatio: 1.0,
).centered()
: const Center(
child: CircularProgressIndicator(
color: Colors.white,
),
),
Align(
alignment: Alignment.bottomCenter,
child: [
if (_isPlaying)
"Playing - ${_selectedRadio!.name} FM".text.makeCentered(),
Icon(
_isPlaying
? CupertinoIcons.stop_circle
: CupertinoIcons.play_circle,
color: Colors.white,
size: 60,
).onInkTap(() {
if (_isPlaying) {
_audioPlayer.stop();
} else {
_audioPlayer.play(_selectedRadio!.url);
}
})
].vStack(),
).pOnly(bottom: context.percentHeight * 12)
],
fit: StackFit.expand,
),
);
}
}
You want me to just give you the corrected code, unfortunately, it's not so simple, I don't know how to fix the code, because I don't know what you want to happen, however I can give you recommendations and I can explain the pros and cons of such recommendations:
_audioPlayer.play(_selectedRadio!.url);
The fact that you get an error in this line means that _selectedRadio is null, and that means that url is not a thing.
After reading your code I noticed you only ever assign _selectedRadio on the e playMusic method, but I don't see you calling that method ever, so you have three options:
First, you can assign a default value to the _selectedRadio to make it never be null
from:
MyRadio? _selectedRadio;
to:
MyRadio _selectedRadio = MyRadio(); // I don't know how you initialize this
Second:
You can check if _selectedRadio is `null
From:
} else {
_audioPlayer.play(_selectedRadio!.url);
}
To;
} else {
if (_selectedRadio != null) {
_audioPlayer.play(_selectedRadio!.url);
}
}
Finally, you could provide some fallback value to play if _selectedRadio is null
From:
_audioPlayer.play(_selectedRadio!.url);
To:
_audioPlayer.play(_selectedRadio?.url ?? 'some other url');
Your decision depends on what you want you app to do.

Object Detection App using Flutter technology not showing Correct Object names

My project is Object detection app using Flutter technology and dart. I have trained my Dataset in a way that...I have created my Own dataset and then trained using The Google teachable machine using TensorFlow lite
app is working absolutely fine the only and main thing which is not working proper is : the app is not showing the correct object name . for eg: the camera is focused on Laptop and it is displaying iy as a tree. Please help me how I can fix it.
My code:
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:tflite/tflite.dart';
import 'main.dart';
//import 'package:splashscreen/splashscreen.dart';
class HomePage extends StatefulWidget{
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage>
{
bool isWorking = false;
String result="";
late CameraController cameraController;
CameraImage? imgCamera;
//late CameraImage imgCamera;
loadModel() async
{
await Tflite.loadModel(
model:"assets/model_unquant.tflite",
labels:"assets/labels.txt",
);
}
initCamera()
{
cameraController = CameraController(cameras[0], ResolutionPreset.medium);
cameraController.initialize().then((value)
{
if(!mounted)
{
return;
}
setState(() {
cameraController.startImageStream((imageFromStream) =>
{
if(!isWorking)
{
isWorking = true,
imgCamera = imageFromStream,
runModelOnStreamFrames(),
}
});
});
});
}
runModelOnStreamFrames() async
{
if(imgCamera != null)
{
var recognitions = await Tflite.runModelOnFrame(
bytesList: imgCamera!.planes.map((plane)
{
return plane.bytes;
}).toList(),
imageHeight: imgCamera!.height,
imageWidth: imgCamera!.width,
imageMean: 127.5,
imageStd: 127.5,
rotation: 90,
numResults: 2,
threshold: 0.1,
asynch:true,
);
result="";
recognitions!.forEach((response)
{
result += response["label"] + " " + (response["confidence"] as double).toStringAsFixed(2) + "\n\n";
});
setState(() {
result;
});
isWorking = false;
}
}
#override
void initState() {
super.initState();
loadModel();
}
#override
void dispose() async
{
super.dispose();
await Tflite.close();
cameraController.dispose();//cameraController?.dispose();
}
#override
Widget build(BuildContext context)
{
return MaterialApp(
home: SafeArea(
child: Scaffold(
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/jarvis.png")
),
),
child: Column(
children: [
Stack(
children: [
Center(
child:Container(
color: Colors.black,
height: 320,
width: 360,
child: Image.asset("assets/camera.png"),
),
),
Center(
child: TextButton(
onPressed: ()
{
initCamera();
},
child: Container(
margin: EdgeInsets.only( top: 35),
height: 270,
width: 360,
child: imgCamera == null
? Container(
height: 330,
width:360,
child:Icon(Icons.photo_camera_front, color: Colors.lightBlueAccent,size: 40,),
)
: AspectRatio(
aspectRatio:cameraController.value.aspectRatio,
child: CameraPreview(cameraController),
),
),
),
),
],
),
Center(
child: Container(
margin: EdgeInsets.only(top: 55.0),
child: SingleChildScrollView(
child:Text(
result,
style:TextStyle(
backgroundColor: Colors.black87,
fontSize: 30.0,
color: Colors.white,
),
textAlign: TextAlign.center,
)
)
)
)
],
),
), //img to background
),
),
);
}
}

The radio starts. But it doesn't stop. It doesn't stop when I switch pages in the project

I want the radio to stop when switching between pages. It works the first time I press the stop and start button, but when I press it again when I want to stop it does not stop. The radio is always on and never turns off. When I close the app completely, the radio stops. I want to do both stop and resume operation on the same button, and I want it to stop when I switch between pages. how can i solve?
code here:
import 'package:flutter/material.dart';
import 'package:flutter_radio/flutter_radio.dart';
class RadioSayfasi extends StatefulWidget {
#override
_RadioSayfasiState createState() => _RadioSayfasiState();
}
class _RadioSayfasiState extends State<RadioSayfasi> {
String url= "https://player.web.tr/listen/d695bfdfb2710f7c53feb05550da66ef";
bool isPlaying= false;
bool isVisible= true;
#override
void initState() {
// TODO: implement initState
super.initState();
audioStart();
}
Future <void> audioStart() async {
await FlutterRadio.audioStart();
print("Radio Başladı");
}
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'IndieXL Online Radio',
debugShowCheckedModeBanner: false,
home: new Scaffold(
appBar: new AppBar(
title: const Text('FM Radio'),
backgroundColor: Colors.blueGrey.shade900,
centerTitle: true,
),
body: Container(
color: Colors.blueGrey.shade900,
child: new Column(
children: <Widget>[
Expanded(
flex: 7,
child: Icon(
Icons.radio, size: 250,
color: Colors.white,
),
),
Expanded(
flex: 2,
child: Padding(
padding: const EdgeInsets.only(right: 40),
child: Align(
alignment: FractionalOffset.center,
child: IconButton(icon: isPlaying? Icon(
Icons.pause_circle_outline,
size: 80,
color: Colors.white,
)
: Icon(
Icons.play_circle_outline,
color: Colors.white,
size: 80,
),
onPressed: (){
setState(() {
FlutterRadio.play(url: url);
isPlaying = !isPlaying;
isVisible = !isVisible;
print("tıkladı");
});
},
),
),
),
),
SizedBox(height: 50,)
],
),
),
));
}
}
I'm guessing the library you mention, https://github.com/thyagoluciano/flutter_radio
To stop radio stream when leaving the screen just override the dispose method
https://github.com/thyagoluciano/flutter_radio/blob/master/lib/flutter_radio.dart#L67
#action
dispose() async {
await FlutterRadio.stop();
}
To start or pause radio stream
https://github.com/thyagoluciano/flutter_radio/blob/master/lib/flutter_radio.dart#L22
onPressed: (){
setState(() {
//FlutterRadio.play(url: url);
FlutterRadio.playOrPause(url: url);
isPlaying = !isPlaying;
isVisible = !isVisible;
print("tıkladı");
});
},

Flutter audio_service play audio in background when mobile screen is locked

I made a radio player app with the code below. Everything works fine when the mobile screen is turned on. But when i turn off my mobile screen the radio stops playing at about 5-8 minutes. I got some tips about using flutter audio_service. (https://pub.dev/packages/audio_service) But i am confused from where should i start. Should i recode again or i can modify this code. Somebody please help me. It would be a grace. Thankyou in advance.
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
class Radio1 extends StatefulWidget {
#override
_Radio1State createState() => _Radio1State();
}
class _Radio1State extends State<Radio1> {
AudioPlayer audioPlayer = AudioPlayer();
#override
void initState() {
super.initState();
AudioPlayer.logEnabled = true;
}
bool _isPlaying = false;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
width: MediaQuery.of(context).size.width,
child: SingleChildScrollView(
child: Column(
children: <Widget>[
//new
SizedBox(
height: 50,
),
//Icon(
// Icons.arrow_drop_down,
//size: 40,
//),
//new
Container(
margin: EdgeInsets.symmetric(horizontal: 20, vertical: 50),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
boxShadow: [
BoxShadow(
color: Color(0x46000000),
offset: Offset(0, 20),
spreadRadius: 0,
blurRadius: 30,
),
BoxShadow(
color: Color(0x11000000),
offset: Offset(0, 10),
spreadRadius: 0,
blurRadius: 30,
),
],
),
//new
child: ClipRRect(
borderRadius: BorderRadius.circular(20),
child: Image(
image: AssetImage("assets/radiologo.jpg"),
width: MediaQuery.of(context).size.width * 0.7,
height: MediaQuery.of(context).size.width * 0.7,
fit: BoxFit.cover,
),
),
),
Text(
"sample text",
style: TextStyle(fontSize: 30, fontWeight: FontWeight.w500),
),
Text(
"(sample text)",
style: TextStyle(fontSize: 12, fontWeight: FontWeight.w500),
),
/* Slider(
value: 10,
onChanged: (v) {},
max: 170,
min: 0,
activeColor: Color(0xFF5E35B1),
), */
Text(
"sample text.",
style: TextStyle(fontSize: 10, fontWeight: FontWeight.w500),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
IconButton(
icon: _isPlaying == false
? Icon(Icons.play_circle_outline)
: Icon(Icons.pause_circle_outline),
iconSize: 60.0,
onPressed: () {
getAudio();
},
),
IconButton(
icon: Icon(Icons.stop),
iconSize: 40,
onPressed: () {
stopAudio();
},
),
//new line
],
),
],
),
),
),
);
}
void getAudio() async {
var url = "http://ia802708.us.archive.org/3/items/count_monte_cristo_0711_librivox/count_of_monte_cristo_001_dumas.mp3";
if (_isPlaying) {
var res = await audioPlayer.pause();
if (res == 1) {
setState(() {
_isPlaying = false;
});
}
} else {
var res = await audioPlayer.play(url);
if (res == 1) {
setState(() {
_isPlaying = true;
});
}
}
}
void stopAudio() async {
int res = await audioPlayer.stop();
if (res == 1) {
setState(() {
_isPlaying = false;
});
}
}
void releaseAUdio() async {
await audioPlayer.stop();
await audioPlayer.release();
}
#override
void dispose() {
super.dispose();
releaseAUdio();
}
}
So as you use the audioplayers package, you'll need to implement the audio_service one to achieve what you want (playing audio in background). Indeed, the audioplayers package is only responsible for playing audio files, and does not handle the background behaviours.
The audio_service is designed to be the only source of truth in your application. So you'll need to re-architecture your code to fit.
But don't delete your code, you might not need many changes in it for the audio.
The package is cut in multiple parts. For example, one for the background tasks, one for the UI to tell the background tasks what you want to do (play, pause, seekTo, ...), so the only changes you might need to do in your code will be to call this part, called AudioService (check the API reference for more informations: https://pub.dev/documentation/audio_service/latest/audio_service/AudioService-class.html).
Once you did that, of course you'll have to implement your background task to achieve your needs.
In summary:
Your code is good, but does not handle the background behaviours.
You may need to implement the audio_service package (or a similar one) to handle the background behaviours.
Please take a look at the audio_session package too to handle the interactions between your app and the different audio interactions on the phone. (For example, handle the notifications received and decrease the volume of your app in consequence).
Hope this answer is helpful for you, good luck :)

i am trying to integrate admob in flutter. it returns null?

i am trying to monitize my app using admob but its really hard to implement it in the app, now everything is set but it gives the following error,"The method 'load' was called on null.
Receiver: null
Tried calling: load()"
can anyone help?
import 'package:carousel_pro/carousel_pro.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:animated_dialog/animated_dialog.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:firebase_admob/firebase_admob.dart';
class Car extends StatefulWidget {
#override
_CarState createState() => _CarState();
}
class _CarState extends State<Car> {
static String adId = 'ca-app-pub-xxxxx92680942917/5470xxxxxx';
String appId = 'ca-app-pub-xxxxxx2680942917~612810xxxx';
MobileAdTargetingInfo targetingInfo;
BannerAd myBanner;
#override
void initState() {
super.initState();
MobileAdTargetingInfo(
keywords: <String>['flutterio', 'beautiful apps'],
contentUrl: 'https://flutter.io',
birthday: DateTime.now(),
childDirected: false,
designedForFamilies: false,
gender: MobileAdGender
.male, // or MobileAdGender.female, MobileAdGender.unknown
testDevices: <String>[], // Android emulators are considered test devices
);
BannerAd(
adUnitId: adId,
size: AdSize.fullBanner,
targetingInfo: targetingInfo,
listener: (MobileAdEvent event) {
print("BannerAd event is $event");
},
);
}
showBanner() {
myBanner
// typically this happens well before the ad is shown
..load()
..show(
// Positions the banner ad 60 pixels from the bottom of the screen
anchorOffset: 0.0,
// Positions the banner ad 10 pixels from the center of the screen to the right
horizontalCenterOffset: 0.0,
// Banner Position
// anchorType: AnchorType.bottom,
);
}
#override
Widget build(
BuildContext context,
) {
return SafeArea(
child: Scaffold(
backgroundColor: Colors.teal[50],
body: StreamBuilder(
stream: Firestore.instance.collection('car').snapshots(),
builder: (context, snapshot) {
if (snapshot.data == null)
return Center(
child: CircularProgressIndicator(
backgroundColor: Colors.red,
valueColor: new AlwaysStoppedAnimation<Color>(Colors.teal),
),
);
return ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) => SingleChildScrollView(
child: Padding(
padding: EdgeInsets.all(8.0),
child: Container(
child: Card(
//shadowColor: Colors.yellow,
child: Column(
children: <Widget>[
//AD
showBanner(),
// Name Container
Container(
alignment: Alignment.center,
decoration: BoxDecoration(
color: Colors.teal[300],
borderRadius: BorderRadius.only(
topRight: Radius.circular(15),
topLeft: Radius.circular(15))),
width: 400,
height: 50,
child: Text(
snapshot.data.documents[index]['item Name'],
style: TextStyle(
fontFamily: 'Baloo',
fontSize: 25,
color: Colors.white,
),
),
),
//item Image///////////////////////////////////////////////////////////////////////////////
i deleted rest of the code cuz it is very long and allowed in here.
That's happening because you didn't initialize your banner. I changed your showBanner function and added a new function to initialize it:
BannerAd createBannerAd() {
return BannerAd(
adUnitId: BannerAd.testAdUnitId,
size: AdSize.banner,
targetingInfo: targetingInfo,
listener: (MobileAdEvent event) {
print("BannerAd event $event");
},
);
}
showBanner() {
_bannerAd ??= createBannerAd();
_bannerAd
..load()
..show(
// Positions the banner ad 60 pixels from the bottom of the screen
anchorOffset: 0.0,
// Positions the banner ad 10 pixels from the center of the screen to the right
horizontalCenterOffset: 0.0,
// Banner Position
// anchorType: AnchorType.bottom,
);
}
You can also do this inside the initState method if you want:
#override
void initState() {
super.initState();
FirebaseAdMob.instance.initialize(appId: "YOUR-APP-ID");
_bannerAd = createBannerAd()..load();
}