Files
Quote-Generator-Client/lib/services/adsense_service_web.dart
ImBenji 7d8e19d1f5
Some checks failed
Build Android App / build (push) Failing after 49s
add macOS support for ad loading and improve timestamp handling
2026-01-02 18:46:12 +00:00

81 lines
2.0 KiB
Dart

import "dart:ui_web" as ui_web;
import "dart:js" as js;
import "package:flutter/widgets.dart";
import "package:universal_html/html.dart" as html;
import "ad_service.dart";
/// Web implementation of AdSense service
class AdSenseService implements AdService {
bool _isLoaded = false;
static const String _adSlotId = "XXXXXXXXXX"; // Replace with your ad slot ID
@override
Future<void> initialize() async {
// AdSense is loaded via script tag in index.html
print("AdSense initialized (web)");
_isLoaded = false;
}
@override
Future<void> loadBannerAd() async {
// AdSense ads are loaded automatically when widget renders
_isLoaded = false;
}
@override
Widget getBannerWidget() {
final viewType = "adsense-banner-${DateTime.now().millisecondsSinceEpoch}";
// Register the view factory
// ignore: undefined_prefixed_name
ui_web.platformViewRegistry.registerViewFactory(
viewType,
(int viewId) => _createAdElement(),
);
return SizedBox(
height: 90,
child: HtmlElementView(viewType: viewType),
);
}
html.Element _createAdElement() {
// Create AdSense div
final adContainer = html.DivElement()
..style.width = "100%"
..style.height = "90px"
..style.textAlign = "center";
final adElement = html.Element.html("""
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-XXXXXXXXXXXXXXXX"
data-ad-slot="$_adSlotId"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
""");
adContainer.append(adElement);
// Push ad using dart:js instead of eval
try {
final adsbygoogle = js.context["adsbygoogle"];
if (adsbygoogle != null) {
adsbygoogle.callMethod("push", [js.JsObject.jsify({})]);
}
} catch (e) {
print("Error pushing AdSense ad: $e");
}
return adContainer;
}
@override
void dispose() {
_isLoaded = false;
}
@override
bool get isLoaded => _isLoaded;
}