Flutter App.
One button that leads to the 2nd page where the content is.
The user clicks on the button and must watch a video ad(rewarded ad).
After the video ad finishes > the user can open the 2nd page / or the 2nd page will be automatically opened when he clicks 'x' on the finished video ad.
My question is > how to do this? What would the code look like and what to use?
Thank you!
Use the following code on your first page above the build method
late RewardedAd _rewardedAd;
bool _isRewardedAdReady = false;
// TODO: Implement _loadRewardedAd()
void _loadRewardedAd() {
RewardedAd.load(
adUnitId: AdHelper.rewardedAdUnitId,
request: AdRequest(),
rewardedAdLoadCallback: RewardedAdLoadCallback(
onAdLoaded: (ad) {
this._rewardedAd = ad;
ad.fullScreenContentCallback = FullScreenContentCallback(
onAdDismissedFullScreenContent: (ad) {
setState(() {
_isRewardedAdReady = false;
});
_loadRewardedAd();
},
);
setState(() {
_isRewardedAdReady = true;
});
},
onAdFailedToLoad: (err) {
print('Failed to load a rewarded ad: ${err.message}');
setState(() {
_isRewardedAdReady = false;
});
},
),
);
}
After that initialize and dispose the rewardedad like
#override
void initState() {
_loadRewardedAd();
super.initState();
}
#override
void dispose() {
_rewardedAd.dispose();
super.dispose();
}
Now call the rewarede ad with Navigating to othe page
GestureDetector(
onTap: () {
if(_isRewardedAdReady){
_rewardedAd.show(onUserEarnedReward:
(RewardedAd ad, RewardItem reward) {
print(
'$ad with reward $RewardItem(${reward.amount}, ${reward.type}');
});
}
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context)=>SecondPage()));
},
child: CustomButton(text:'GoTo Second Page')
),
for better understand go to here
Related
I have a flutter's ElevatedButton to show a rewardedAd. It shows a string:'show ad' initially. But after watching an ad, i want to display an int:'+10' inside it. Also, I want to increment +10 every time I click on it (watch an ad).
my code:
RewardedAd? _rewardedAd;
int _rewardedScore = 0;
#override
void initState() {
// TODO: implement initState
super.initState();
_createRewardedAd();
}
void _createRewardedAd() {
RewardedAd.load(
adUnitId: 'ca-app-pub-3940256099942544/5224354917',
request: AdRequest(),
rewardedAdLoadCallback: RewardedAdLoadCallback(
onAdLoaded: (RewardedAd ad) {
print('$ad loaded.');
// Keep a reference to the ad so you can show it later.
setState(() => this._rewardedAd = ad);
},
onAdFailedToLoad: (LoadAdError error) {
print('RewardedAd failed to load: $error');
setState(() {
_rewardedAd = null;
});
},
),
);
}
void _showRewardedAd() {
_rewardedAd?.fullScreenContentCallback = FullScreenContentCallback(
onAdShowedFullScreenContent: (RewardedAd ad) =>
print('$ad onAdShowedFullScreenContent.'),
onAdDismissedFullScreenContent: (RewardedAd ad) {
print('$ad onAdDismissedFullScreenContent.');
ad.dispose(); // dispose ad and
_createRewardedAd(); // then, create a new one
},
onAdFailedToShowFullScreenContent: (RewardedAd ad, AdError error) {
print('$ad onAdFailedToShowFullScreenContent: $error');
ad.dispose(); // dispose ad and
_createRewardedAd(); // then, create a new one
},
onAdImpression: (RewardedAd ad) => print('$ad impression occurred.'),
);
_rewardedAd?.show(
onUserEarnedReward: (AdWithoutView ad, RewardItem reward) {
setState(() {
_rewardedScore = _rewardedScore + 10;
});
});
_rewardedAd = null;
}
Scaffold(
appBar: AppBar(
title: Text('Rewarded: $_rewardedScore'),
centerTitle: true,
),
body: Center(
child: ElevatedButton(
child: Text(
"show ad",
style: TextStyle(fontSize: 30),
),
onPressed: () {
print('clicked rewarded');
_showRewardedAd();
},
),
),
);
You can either Text(reward.toString()) with int reward
Or (int.parse(reward)+10).toString() with string reward
"I figured it out! Time travel! I figured it out".
we go back to time, and bring back the Text() stones, and snap both string and int back back to reality.
make a bool variable.
bool clickedButton = false;
Then, use Ternary Operator to store one of these values:
either the int variable: +10 (if true)
or the string: "Show ad" (if false, as by default)
edit the Text() widget as:
Text(
clickedButton? '$_rewardedScore' : 'Show Ad',
style: TextStyle(fontSize: 30),
)
Make a nullable String type variable like
String? showAd;
and use it like
Text(showAd ?? "show ad");
For incrementing the value write a function like this
showAd = watchAd(showAd)
String watchAd(String? ad){
int _newValue = int.parse(ad ?? '0');
_newValue+=10;
return _newValue.toString();
}
I only use interstitial in the app. An interstitial ad appears on the first click on app launch, and it takes 15 clicks for the ad to appear again.
The problem is that when I exit the app and re-enter after a while, it doesn't show ads on the first click. In fact, sometimes the problem of not showing ads on the first click takes a few days. But after 15 clicks it shows ads.
What I want to do is show an ad on the first click of users every time they enter the app. I'm not sure if this is a bug or something with the code.
PS: I am using getx state management - The ad impression limit is limited to 5 times a day per user.
Interstitial ad controller:
class AdController extends GetxController {
InterstitialAd? interstitialAd;
int adCounter = 0;
int interstitialLoadAttempts = 0;
int maxAttempts = 3;
void onAdLoaded(InterstitialAd ad) {
interstitialAd = ad;
interstitialLoadAttempts = 0;
interstitialAd?.fullScreenContentCallback = FullScreenContentCallback(
onAdDismissedFullScreenContent: (ad) {
interstitialAd?.dispose();
initAd();
},
onAdFailedToShowFullScreenContent: (ad, error) {
interstitialAd?.dispose();
initAd();
},
);
}
void initAd() {
InterstitialAd.load(
adUnitId: AdHelper.interstitialAdUnitId,
request: const AdRequest(),
adLoadCallback: InterstitialAdLoadCallback(
onAdLoaded: onAdLoaded,
onAdFailedToLoad: (error) {
interstitialLoadAttempts++;
interstitialAd = null;
if (interstitialLoadAttempts <= maxAttempts) {
initAd();
}
},
),
);
}
void getAd() {
if (adCounter % 15 == 0 && interstitialAd != null) {
interstitialAd?.show();
interstitialAd = null;
}
adCounter++;
}
#override
void onInit() {
initAd();
super.onInit();
}
#override
void dispose() {
interstitialAd?.dispose();
super.dispose();
}
}
Ad display:
AdController AdController = Get.put(AdController());
return Padding(
padding: EdgeInsets.symmetric(
horizontal: 7.w,
vertical: 8.h, ),
child: GestureDetector(
onTap: () {
AdController.getAd();
Get.to( const ContentIndex(),
transition: Transition.native,
duration: const Duration(milliseconds: 250),
arguments: contentDex, );
I need to hide button after 1 mins but while reloading and again restarting application it will not show again once it hide it will not repeated
Use shared_preferences (or any persist memory) to persist the state of the button over restarts.
See Store key-value data on disk for details.
You need to use db to handle restarting application case.
You can use shared_preferences to store a flag about visibility.
class _GState extends State<G> {
static const String _buttonVisibilityKey = "DoneWIthButtonX";
bool showButton = false;
#override
void initState() {
super.initState();
_buttonActionChecker().then((value) async {
// return false if button never showed up, activate the timer to hide
print(value);
if (!value) {
showButton = true;
setState(() {});
Future.delayed(Duration(minutes: 1)).then((value) async {
showButton = false;
SharedPreferences.getInstance()
.then((value) => value.setBool(_buttonVisibilityKey, true));
setState(() {});
});
}
});
}
#override
void dispose() {
super.dispose();
}
/// is the button have been shown already return true
Future<bool> _buttonActionChecker() async {
return SharedPreferences.getInstance().then((value) {
return value.getBool(_buttonVisibilityKey) ?? false;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: showButton
? FloatingActionButton(
onPressed: () {
setState(() {});
},
)
: null,
);
}
}
I need to redirect user to auth page when app is inactive for 5 minutes. I suppose using WidgetsBindingObserver. I detect when app is inactive for 5 minutes, but i don't know how to redirect user to auth page.
Here's part of my code:
#override
void initState() {
super.initState();
homeScreen = widget.homeScreen;
WidgetsBinding.instance.addObserver(this);
}
#override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
#override
void didChangeAppLifecycleState(AppLifecycleState state) {
setState(() {
if (state == AppLifecycleState.paused) {
Future.delayed(Duration(seconds: 3), () {
setState(() {
// navigate to auth page
});
});
}
});
}
You can use the Navigator:
Navigator.push(context,
MaterialPageRoute(builder: (context) => AuthPage()));
You don't need redirect an app in 5 minutes, you can redirect it when user want to navigate into page (or to do some action) which needed to be authenticated, just log last action timestamp into SharedPreferences and check this timestamp on every needed-auth action.
I am setting ads in flutter app using firebase_admob plugin. I tried banner ad and it is working fine but, when i navigate to another page it still remains at its position. I want that ad should hide when navigating to another page.
The code snippet is as follows.
BannerAd myBanner = BannerAd(
// Replace the testAdUnitId with an ad unit id from the AdMob dash.
// https://developers.google.com/admob/android/test-ads
// https://developers.google.com/admob/ios/test-ads
adUnitId: BannerAd.testAdUnitId,
size: AdSize.smartBanner,
targetingInfo: targetingInfo,
listener: (MobileAdEvent event) {
print("BannerAd event is $event");
},
);
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: 60.0,
// Banner Position
anchorType: AnchorType.bottom,
);
You can use RouteObserver:
class AdmobObserver extends RouteObserver<PageRoute<dynamic>> {
BannerAd _myBanner = BannerAd(
adUnitId: BannerAd.testAdUnitId,
size: AdSize.smartBanner,
listener: (MobileAdEvent event) {
print("BannerAd event is $event");
},
);
#override
void didPush(Route route, Route previousRoute) {
super.didPush(route, previousRoute);
if (route.settings.name == '/') {
// show the banner when navigating to home screen
_showBannerAd();
} else {
// hide the banner when navigating to another screen
_myBanner.dispose();
}
}
#override
void didPop(Route route, Route previousRoute) {
super.didPop(route, previousRoute);
if (previousRoute.settings.name == '/') {
// show the banner again when returning back to the home screen
_showBannerAd();
}
}
void _showBannerAd() {
_myBanner
..load()
..show(
anchorOffset: 60.0,
// Banner Position
anchorType: AnchorType.bottom,
);
}
}
Then you need to add this observer to your MaterialApp:
static AdmobObserver admobObserver = AdmobObserver();
#override
Widget build(BuildContext context) {
return MaterialApp(
navigatorObservers: <NavigatorObserver>[admobObserver],
.
.
.
dispose() will be called when a page is destroyed. So you can distroy banner ad there.
#override
void dispose() {
myBanner.dispose();
super.dispose();
}
if you want to hide when show new Screen and re show when user return to last screen, you need to dispose before start new page and use async and await to await until new page pop from navigator, lets show some code
BannerAd bannerAd;
#override
void initState() {
super.initState();
initAds();
}
void openNewPage() async{
//hide banner before start new page
bannerAd?.dispose();
await Navigator.push(context, MaterialPageRoute(builder: (_) => MySecondScreen()));
//now user is return to this page so reshow banner
initAds();
}
#override
void dispose() {
super.dispose();
bannerAd?.dispose();
interstitialAd?.dispose();
}
void initAds() async {
bannerAd = BannerAd(
adUnitId: kReleaseMode ? Constant.BANNER_AD_ID : BannerAd.testAdUnitId,
size: AdSize.smartBanner,
listener: (MobileAdEvent event) {
print("BannerAd event is $event");
},
);
bannerAd
// typically this happens well before the ad is shown
..load()
..show(
anchorType: AnchorType.bottom,
);
}
so inside this method we hide/reshow banner
void openNewPage() async{
//hide banner before start new page
bannerAd?.dispose();
await Navigator.push(context, MaterialPageRoute(builder: (_) => MySecondScreen()));
//now user is return to this page so reshow banner
initAds();
}
call Navigator.pop();
before calling Navigator.push() . This will solve your problem
Follow these steps.
Consider two pages/screens as HomePage and SecondPage.
Step 1. Add this code in HomePage to go to SecondPage
myBanner?.dispose();
myBanner = null;
Navigator.push(context,
MaterialPageRoute(builder: (context) => SecondPage()));
this will remove BannerAd object and banner will be disappeared.
Step 2. Add this code in SecondPage
Timer(Duration(seconds: 3), () {
if(secondPageBanner == null){
initState();
}
});
Put your BannerAd initialization/ Declaration code into initState() function.
This will show Banner in SecondPage.
Step 3. Add this code in SecondPage when back to Homepage
secondPageBanner?.dispose();
if(secondPageBanner != null){
secondPageBanner = null;
}
setState(() {
Navigator.pop(context);
});
This will make secondPageBanner hidden.
Step 4. Add this code in Homepage
Timer(Duration(seconds: 3), () {
if(myBanner == null){
initState();
}
});
OR like this
void function(){
if(myBanner == null){
initState();
}
}
in a button click function that button is normally clicked by user.
This will show myBanner Ad again in HomePage.