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();
},
),
),
);
3
Answers
"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.
Then, use Ternary Operator to store one of these values:
edit the Text() widget as:
You can either Text(reward.toString()) with int reward
Or (int.parse(reward)+10).toString() with string reward
Make a nullable String type variable like
and use it like
For incrementing the value write a function like this