adUnitId is not showing google banner ads in flutter - flutter

I'm trying to implement google ads through admob_flutter package, created adunitId through admob account. but these adUnitId are not showing ads.
when I'm using ca-app-pub-3940256099942544/2934735716 this adUnitId then it is showing test ads on google ad.
Here is my code:
import 'dart:async';
import 'dart:io';
import 'package:admob_flutter/admob_flutter.dart';
import 'package:flutter/material.dart';
class GoogleAdBanner extends StatefulWidget {
GoogleAdBanner(this.size);
final AdmobBannerSize size;
#override
State<StatefulWidget> createState() => BannerAdState();
}
class BannerAdState extends State<GoogleAdBanner> {
AdmobBanner _bannerAd;
final Completer<AdmobBanner> bannerCompleter = Completer<AdmobBanner>();
#override
void initState() {
super.initState();
Admob.requestTrackingAuthorization();
}
String getBannerAdUnitId() {
if (Platform.isIOS) {
return 'ca-app-pub-7282911616152886/6377817226';
} else if (Platform.isAndroid) {
return 'ca-app-pub-7282911616152886/8046122111';
}
return null;
}
void handleEvent(
AdmobAdEvent event, Map<String, dynamic> args, String adType) {
switch (event) {
case AdmobAdEvent.loaded:
print('New Admob $adType Ad loaded!');
break;
case AdmobAdEvent.opened:
print('Admob $adType Ad opened!');
break;
case AdmobAdEvent.closed:
print('Admob $adType Ad closed!');
break;
case AdmobAdEvent.failedToLoad:
print('Admob $adType failed to load. :(');
break;
default:
}
}
#override
Widget build(BuildContext context) {
return AdmobBanner(
adUnitId: getBannerAdUnitId(), //'ca-app-pub-3940256099942544/2934735716',
adSize: widget.size,
listener: (AdmobAdEvent event,
Map<String, dynamic> args) {
handleEvent(event, args, 'Banner');
},
onBannerCreated: (AdmobBannerController controller) {},
);
}
}
using it as
GoogleAdBanner(AdmobBannerSize.LARGE_BANNER)
Please help with this. Thanks in advance!

Real ads are displayed only when there are enough number of requests. The inventory is empty till the threshold has reached. If you are able to see the test ads you can be assured that the implementation is right. Make sure you change the ad app id in manifest and info.plist and add the right ad unit ad in ad request before release.

use getBannerAdUnitId() like this:-
String get BannerAdUnitId(){
//body
}
adUnitId: BannerAdUnitId(),

Related

Why Flutter hybrid app does not start? I have used webview and google mobad that should show an ad when the app started

I am about to create an app using webview in flutter language and I want to show open app in mobad when the app opened or started.
The code you provided is written in Dart programming language. It initializes an instance of the "AppOpenAdManager" class and calls the "loadAd" method on it. Then, it initializes an instance of the "AppLifecycleReactor" class and passes the "appOpenAdManager" instance to its constructor.
The purpose of this code is to load and manage an advertisement using the "AppOpenAdManager" class, and to monitor the lifecycle events of the app using the "AppLifecycleReactor" class.
I am very new to flutter, thank you for helping me.
here's main.dart
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:factorial/app_open_ad_manager.dart';
import 'app_lifecycle_reactor.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
MobileAds.instance.initialize();
late AppLifecycleReactor _appLifecycleReactor;
AppOpenAdManager appOpenAdManager = AppOpenAdManager()..loadAd();
_appLifecycleReactor =
AppLifecycleReactor(appOpenAdManager: appOpenAdManager);
runApp(
const MaterialApp(
debugShowCheckedModeBanner: false,
home: WebViewApp(),
),
);
}
class WebViewApp extends StatefulWidget {
const WebViewApp({super.key});
#override
State<WebViewApp> createState() => _WebViewAppState();
}
class _WebViewAppState extends State<WebViewApp> with WidgetsBindingObserver {
late final WebViewController controller;
#override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..loadRequest(
Uri.parse('https://example.com'),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: WebViewWidget(
controller: controller,
),
);
}
}
here's app_open_ad_manager.dart
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'dart:io' show Platform;
class AppOpenAdManager {
String adUnitId = Platform.isAndroid
? 'ca-app-pub-3940256099942544/3419835294'
: 'ca-app-pub-3940256099942544/5662855259';
AppOpenAd? _appOpenAd;
bool _isShowingAd = false;
void loadAd() {
AppOpenAd.load(
adUnitId: adUnitId,
orientation: AppOpenAd.orientationPortrait,
request: AdRequest(),
adLoadCallback: AppOpenAdLoadCallback(
onAdLoaded: (ad) {
_appOpenAd = ad;
},
onAdFailedToLoad: (error) {
print('AppOpenAd failed to load: $error');
// Handle the error.
},
),
);
}
void showAdIfAvailable() {
if (!isAdAvailable) {
print('Tried to show ad before available.');
loadAd();
return;
}
if (_isShowingAd) {
print('Tried to show ad while already showing an ad.');
return;
}
// Set the fullScreenContentCallback and show the ad.
_appOpenAd!.fullScreenContentCallback = FullScreenContentCallback(
onAdShowedFullScreenContent: (ad) {
_isShowingAd = true;
print('$ad onAdShowedFullScreenContent');
},
onAdFailedToShowFullScreenContent: (ad, error) {
print('$ad onAdFailedToShowFullScreenContent: $error');
_isShowingAd = false;
ad.dispose();
_appOpenAd = null;
},
onAdDismissedFullScreenContent: (ad) {
print('$ad onAdDismissedFullScreenContent');
_isShowingAd = false;
ad.dispose();
_appOpenAd = null;
loadAd();
},
);
}
/// Whether an ad is available to be shown.
bool get isAdAvailable {
return _appOpenAd != null;
}
}
and here's
import 'app_open_ad_manager.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
/// Listens for app foreground events and shows app open ads.
class AppLifecycleReactor {
final AppOpenAdManager appOpenAdManager;
AppLifecycleReactor({required this.appOpenAdManager});
void listenToAppStateChanges() {
AppStateEventNotifier.startListening();
AppStateEventNotifier.appStateStream
.forEach((state) => _onAppStateChanged(state));
}
void _onAppStateChanged(AppState appState) {
// Try to show an app open ad if the app is being resumed and
// we're not already showing an app open ad.
if (appState == AppState.foreground) {
appOpenAdManager.showAdIfAvailable();
}
}
}
I was following this Tutorial and I got all the codes there.

Flutter interstitial ad with AppOpen ads

Currently Im using native_admob_flutter for my flutter app. I also included AppOpenAds and Interstital ad within the app.
I want to display the AppOpen ad when user open the app/ resume to the app, here is how I do it in main.dart:
#override
Future<void> didChangeAppLifecycleState(AppLifecycleState state) async {
switch (state) {
case AppLifecycleState.resumed:
loadAndDisplayAppOpenAd();
break;
case AppLifecycleState.inactive:
break;
case AppLifecycleState.paused:
break;
case AppLifecycleState.detached:
break;
}
}
However I found that displaying Interstial ad will also change the app state -> inactive -> paused -> resume, which trigger AppOpen ad.
This really create bad user experinence. Is there a way to overcome this? Thank you!
You may need a variable to make sure that app has been paused by user action, and not by interstitial.
static bool pausedByInterstitial = false;
...
class AppLifecycleReactor extends WidgetsBindingObserver {
final AppOpenAdManager appOpenAdManager;
AppLifecycleReactor({required this.appOpenAdManager});
static bool pausedByInterstitial = false;
#override
Future<void> didChangeAppLifecycleState(AppLifecycleState state) async {
if (state == AppLifecycleState.resumed && !pausedByInterstitial) {
appOpenAdManager.showAdIfAvailable();
}
}
}
...
showInter() {
AppLifecycleReactor.pausedByInterstitial = true;
InterstitialListener(
...
onAdHiddenCallback: (ad) {
AppLifecycleReactor.pausedByInterstitial = false;
},
...
);
}

Flutter : is it possible to implement a snackbar one time in main.dart for example for all screen when the connectivity status changed

i make an enum for a connectivity :
enum ConnectivityStatus{
Wifi,
Cellular,
Offline
}
then i create a service to check the Connectivity :
import 'dart:async';
import 'package:Zabatnee/activities_app/enum/connectivity_status.dart';
import 'package:connectivity/connectivity.dart';
class ConnectivityService{
StreamController<ConnectivityStatus> connectionStatusController = StreamController<ConnectivityStatus>();
ConnectivityService(){
Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
var connectionStatus = _getStatusFromResult(result);
connectionStatusController.add(connectionStatus);
});
}
ConnectivityStatus _getStatusFromResult(ConnectivityResult result) {
switch (result) {
case ConnectivityResult.mobile:
return ConnectivityStatus.Cellular;
case ConnectivityResult.wifi:
return ConnectivityStatus.Wifi;
case ConnectivityResult.none:
return ConnectivityStatus.Offline;
default:
return ConnectivityStatus.Offline;
}
}
}
and what i need is to check the connectivity status in all screen that i created. Can I do it once for all screens all, or i must check the connnectivity for each one individually.
You can check the connectivity status once & that will be implemented for all of your app.
You just have to create a wrapper class & subscribe to the Connectivity stream & apply the logic in this wrapper class.
Your whole widget will be wrapped by this widget.
MaterialApp(
..
home: ConnectivityWrapper(
childWidget: YourWidget(), // replace this with your own home widget
),
);
The wrapper widget will look something like this:
class ConnectivityWrapper extends StatefulWidget {
ConnectivityWrapper(this.childWidget);
final Widget childWidget;
#override
_ConnectivityWrapperState createState() => _ConnectivityWrapperState();
}
class _ConnectivityWrapperState extends State<ConnectivityWrapper> {
StreamSubscription<ConnectivityStatus> subscription;
#override
void initState() {
super.initState();
subscription = connectionStatusController.stream.listen((status)
{
if(status == ConnectivityStatus.Offline) {
// Your logic here (Toast message or something else)
}
},
onDone() {
// Your logic here
},
onError: () {
// Your logic here
});
}
#override
Widget build(BuildContext context) {
return widget.childWidget;
}
#override
void dispose() {
// unsubscribe to the stream
subscription.cancel();
super.dispose();
}
}

Flutter: could not find the Provider above FutureBuilder

I'm trying to navigate to a screen where depending on 3 factors:
If the app has run before or not
If the user is null or not
If the email is verified or not.
import 'package:client/providers/auth_provider.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../screens/home_screen.dart';
import '../screens/login_screen.dart';
class Wrapper extends StatefulWidget {
#override
_WrapperState createState() => _WrapperState();
}
class _WrapperState extends State<Wrapper> {
FirebaseAuth auth = FirebaseAuth.instance;
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext ctx) {
return FutureBuilder(
future: hasAlreadyStarted(),
builder: (ctx, snapshot) {
return Provider.of<User>(ctx) != null &&
snapshot.data == true &&
AuthProvider().isEmailVerified
? HomeScreen()
: LoginScreen();
});
}
Future<bool> hasAlreadyStarted() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
try {
if (prefs.getBool("hasRun") == null) {
await AuthProvider().logout();
setState(() {
prefs.setBool("hasRun", true);
});
return true;
} else {
return true;
}
} catch (error) {
setState(() {
prefs.setBool("hasRun", null);
});
return false;
}
}
}
The screen works fine on it's own, but when i Navigate from a different screen it gives me the error.
Could not find the correct Provider<User> above this FutureBuilder<bool> Widget
Can you explain the error and give me a solution. Thanks :D
I just needed to wrap the entire MaterialApp with the StreamProvider

Get HTML element with web scraping on flutter

i´m trying to get the link of the video of this page with the package "web_scraper". I can find it using Chrome´s tools (is an attribute of a jw-video jw-reset element. The problem is that when you enter the page you can´t see this attribute before clicking in the play button. Can any one help me?
I have already this code:
import 'package:flutter/material.dart';
import 'package:web_scraper/web_scraper.dart';
class Prueba extends StatefulWidget {
#override
State createState() => new _Prueba();
}
class _Prueba extends State<Prueba> {
final webScraper = WebScraper('https://www3.animeflv.net');
List<Map<String, dynamic>> link;
void fetchProducts() async {
// Loads web page and downloads into local state of library
if (await webScraper
.loadWebPage('/ver/sword-art-online-alicization-war-of-underworld-20')) {
setState(() {
link = webScraper.getElement(
'div.jw-wrapper.jw-reset > div.jw-media.jw-reset > video.jw-video.jw-reset', ['src']);
});
}
}
#override
void initState() {
super.initState();
// Requesting to fetch before UI drawing starts
fetchProducts();
}
#override
Widget build (BuildContext ctxt) {
print(link);
return Container();
}
}