### addProvider Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-manager.md Example demonstrating initial setup with addProviders and then dynamically adding another provider using addProvider. ```dart // Initial setup GTAdsManager.instance.addProviders([csjProvider, ylhProvider]); // Later, add another provider dynamically GTAdsManager.instance.addProvider(sigmobProvider); ``` -------------------------------- ### GTAds.init() Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/configuration.md Example of initializing GTAds and registering providers. ```dart void main() async { WidgetsFlutterBinding.ensureInitialized(); // Register providers GTAds.addProviders([ GTAdsCsjProvider("csj", "5098580", "5098580", appName: "MyApp"), GTAdsYlhProvider("ylh", "1234567890", "1234567890"), ]); // Initialize final results = await GTAds.init(isDebug: true); // results: [{"csj": true}, {"ylh": true}] runApp(MyApp()); } ``` -------------------------------- ### init Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads.md Example of initializing ad providers and handling the results. ```dart Future setupAds() async { GTAds.addProviders([ GTAdsCsjProvider("csj", androidId: "5098580", iosId: "5098580", appName: "MyApp"), GTAdsYlhProvider("ylh", androidId: "1234567890", iosId: "1234567890"), ]); final results = await GTAds.init(isDebug: true); // results: [{'csj': true}, {'ylh': true}] for (var result in results) { result.forEach((alias, success) { print('$alias initialized: $success'); }); } } ``` -------------------------------- ### addProviders Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads.md Example of adding multiple ad providers at once. ```dart GTAds.addProviders([ GTAdsCsjProvider("csj", androidId: "5098580", iosId: "5098580", appName: "MyApp"), GTAdsYlhProvider("ylh", androidId: "1234567890", iosId: "1234567890"), GTAdsSigmobProvider("sigmob", androidId: "9876543210", iosId: "9876543210"), ]); ``` -------------------------------- ### getProvider Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads.md Example of retrieving an ad provider by its alias. ```dart // Get the ByteDance Pangle provider final csjProvider = GTAds.getProvider("csj"); if (csjProvider != null) { print("CSJ provider found"); } // Get the Tencent provider final ylhProvider = GTAds.getProvider("ylh"); ``` -------------------------------- ### GTAdsYlhProvider Configuration Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/configuration.md Example of configuring GTAdsYlhProvider. ```dart final ylhProvider = GTAdsYlhProvider( "ylh", androidId: "1234567890", iosId: "1234567890", ); GTAds.addProvider(ylhProvider); ``` -------------------------------- ### GTAdsProvider Base Configuration Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/configuration.md Example of configuring a base GTAdsProvider. ```dart final csjProvider = GTAdsCsjProvider( "csj", // alias androidId: "5098580", // Android ID iosId: "5098580", // iOS ID appName: "MyApp" // Provider-specific param ); GTAds.addProvider(csjProvider); ``` -------------------------------- ### onFinish Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-callback.md Example of using the onFinish callback to indicate ad completion. ```dart callBack: GTAdsCallBack( onFinish: (code) { print("User watched ad from ${code.alias} to completion"); }, ) ``` -------------------------------- ### Responsive Sizing Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-widgets.md Example of adapting ad dimensions based on screen orientation. ```dart final mediaQuery = MediaQuery.of(context); final isPortrait = mediaQuery.orientation == Orientation.portrait; GTAdsBannerWidget( codes: adCodes, width: isPortrait ? 300 : 728, height: isPortrait ? 400 : 90, timeout: 5, ) ``` -------------------------------- ### Example - Offer reward option before ad Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-full-screen-ads.md Example showing a dialog to prompt the user if they want to watch an ad for rewards. ```dart void promptForRewardAd(BuildContext context) { showDialog( context: context, builder: (context) => AlertDialog( title: Text("Watch an ad for rewards?"), content: Text("Watch a 30-second ad to earn 100 Gold Coins"), actions: [ TextButton( onPressed: () => Navigator.pop(context), child: Text("No thanks"), ), TextButton( onPressed: () { Navigator.pop(context); showRewardAd(); }, child: Text("Yes, show ad"), ), ], ), ); } ``` -------------------------------- ### Constructor Usage Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-callback.md Example demonstrating how to instantiate GTAdsCallBack with specific event handlers. ```dart final callback = GTAdsCallBack( onShow: (code) => print("Ad loaded: ${code.alias}"), onFail: (code, message) => print("Ad failed: $message"), onClick: (code) => print("Ad clicked"), ); ``` -------------------------------- ### Complete Usage Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-callback.md A comprehensive example demonstrating the usage of GTAdsBannerWidget with various callback events. ```dart GTAdsBannerWidget( codes: [ GTAdsCode(alias: "csj", probability: 5, androidId: "102735527", iosId: "102735527"), GTAdsCode(alias: "ylh", probability: 3, androidId: "8042711873318113", iosId: "5004358713683949"), ], width: 300, height: 400, timeout: 5, model: GTAdsModel.RANDOM, callBack: GTAdsCallBack( onShow: (code) { print("✓ Ad shown from ${code.alias}"); setState(() => isAdVisible = true); }, onFail: (code, message) { print("✗ ${code?.alias} failed: $message"); // Framework will automatically retry next provider }, onClick: (code) { print("→ User clicked ${code.alias}"); analytics.logEvent('ad_click', {'provider': code.alias}); }, onClose: (code) { print("← User closed ${code.alias}"); }, onTimeout: () { print("⏱ Ad loading timed out"); setState(() => isAdVisible = false); }, onEnd: () { print("⊗ All ads failed"); setState(() => isAdVisible = false); }, ), ) ``` -------------------------------- ### Example - Grant in-game currency Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-full-screen-ads.md Example demonstrating how to show a reward ad and grant in-game currency upon successful verification. ```dart void showRewardAd() async { final success = await GTAds.rewardAd( codes: [ GTAdsCode( alias: "csj", probability: 5, androidId: "945418088", iosId: "945418088" ), GTAdsCode( alias: "ylh", probability: 3, androidId: "9876543210", iosId: "1234567890" ), ], rewardName: "Gold Coins", rewardAmount: 100, userId: "user_${currentUser.id}", customData: "daily_chest_reward", timeout: 10, model: GTAdsModel.PRIORITY, callBack: GTAdsCallBack( onShow: (code) { print("Reward ad from ${code.alias} is showing"); pauseGame(); }, onFail: (code, message) { print("Reward ad failed: $message"); // Framework auto-retries }, onFinish: (code) { print("User watched the entire video"); }, onVerify: (code, verify, transId, rewardName, rewardAmount) { if (verify) { print("Reward verified! Granting $rewardAmount $rewardName"); playerService.addCurrency( currencyType: "gold", amount: rewardAmount, reason: "video_reward", transactionId: transId, ); showToast("Earned $rewardAmount $rewardName!"); } else { print("Reward verification failed"); showToast("Reward could not be verified"); } }, onClose: (code) { print("Reward ad closed"); resumeGame(); }, onExpand: (code, param) { // Provider-specific extended data print("Extended reward data: $param"); }, onTimeout: () { print("Reward ad loading timed out"); resumeGame(); }, onEnd: () { print("All reward ads failed to load"); resumeGame(); }, ), ); if (!success) { print("Could not start reward ad"); resumeGame(); } } ``` -------------------------------- ### Complete Initialization Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/configuration.md Demonstrates the full process of configuring and initializing GTAds providers, and setting up banner and reward ads. ```dart import 'package:flutter/material.dart'; import 'package:gtads/gtads.dart'; import 'package:gtads_csj/gtads_csj.dart'; import 'package:gtads_ylh/gtads_ylh.dart'; import 'package:gtads_sigmob/gtads_sigmob.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); // Step 1: Configure providers GTAds.addProviders([ GTAdsCsjProvider( "csj", androidId: "5098580", iosId: "5098580", appName: "MyGame", useMediation: true, ), GTAdsYlhProvider( "ylh", androidId: "1234567890", iosId: "1234567890", ), GTAdsSigmobProvider( "sigmob", androidId: "9876543210", iosId: "9876543210", ), ]); // Step 2: Initialize providers final results = await GTAds.init(isDebug: true); print("Provider initialization: $results"); runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: GameScreen(), ); } } class GameScreen extends StatelessWidget { // Banner ad codes static const bannerCodes = [ GTAdsCode( alias: "csj", probability: 50, androidId: "945410197", iosId: "945410197", ), GTAdsCode( alias: "ylh", probability: 30, androidId: "8042711873318113", iosId: "5004358713683949", ), GTAdsCode( alias: "sigmob", probability: 20, androidId: "945410197", iosId: "945410197", ), ]; // Reward ad codes static const rewardCodes = [ GTAdsCode( alias: "csj", probability: 50, androidId: "945418088", iosId: "945418088", ), GTAdsCode( alias: "ylh", probability: 50, androidId: "9876543210", iosId: "1234567890", ), ]; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("Game")), body: Column( children: [ // Banner ad GTAdsBannerWidget( codes: bannerCodes, width: 320, height: 50, timeout: 5, model: GTAdsModel.RANDOM, ), Expanded( child: Center( child: ElevatedButton( onPressed: () => showRewardAd(context), child: Text("Watch Ad for Reward"), ), ), ), ], ), ); } Future showRewardAd(BuildContext context) async { await GTAds.rewardAd( codes: rewardCodes, rewardName: "Gold Coins", rewardAmount: 100, userId: "user123", customData: "reward_button", timeout: 10, callBack: GTAdsCallBack( onShow: (code) => print("Reward ad shown"), onVerify: (code, verify, transId, name, amount) { if (verify) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text("Earned $amount $name!")), ); } }, ), ); } } ``` -------------------------------- ### Example - Multiple reward types Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-full-screen-ads.md Example demonstrating how to handle multiple reward types based on an enum. ```dart Future showRewardForAction(RewardType rewardType) async { final (rewardName, rewardAmount) = switch (rewardType) { RewardType.coins => ("Gold Coins", 50), RewardType.gems => ("Gems", 5), RewardType.booster => ("Speed Booster", 1), }; await GTAds.rewardAd( codes: rewardAdCodes, rewardName: rewardName, rewardAmount: rewardAmount, userId: currentUser.id, customData: rewardType.toString(), timeout: 10, callBack: GTAdsCallBack( onVerify: (code, verify, transId, name, amount) { if (verify) { playerService.grantReward(rewardType, amount, transId); } }, onClose: (code) => resumeGame(), onEnd: () => resumeGame(), ), ); } ``` -------------------------------- ### removeProvider Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-manager.md Example showing how to remove a provider by its alias and then verifying its removal. ```dart // Remove a specific provider GTAdsManager.instance.removeProvider("csj"); // Verify it's removed final csjProvider = GTAds.getProvider("csj"); print(csjProvider == null); // Output: true ``` -------------------------------- ### addProvider Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads.md Example of adding ByteDance Pangle and Tencent Youlianghui ad providers. ```dart // Add ByteDance Pangle ad provider GTAds.addProvider( GTAdsCsjProvider( "csj", androidId: "5098580", iosId: "5098580", appName: "MyApp" ) ); // Add Tencent Youlianghui provider GTAds.addProvider( GTAdsYlhProvider( "ylh", androidId: "1234567890", iosId: "1234567890" ) ); ``` -------------------------------- ### Example Implementation of rewardAd Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-provider.md An example implementation of the rewardAd method demonstrating how to load and display a reward video ad using a hypothetical MyAdNetwork. ```dart @override StreamSubscription? rewardAd( GTAdsCode adCode, String rewardName, int rewardAmount, String userId, String customData, GTAdsCallBack? callBack ) { if (adCode.androidId == null && adCode.iosId == null) { return null; } StreamSubscription? subscription; MyAdNetwork.loadRewardAd( androidAdId: adCode.androidId ?? "", iosAdId: adCode.iosId ?? "", userId: userId, customData: customData, onLoaded: () { callBack?.onShow?.call(adCode); MyAdNetwork.showRewardAd(); }, onFailed: (error) { callBack?.onFail?.call(adCode, error); subscription?.cancel(); }, onClicked: () => callBack?.onClick?.call(adCode), onClosed: () => callBack?.onClose?.call(adCode), onVerified: (isValid, transactionId) { callBack?.onVerify?.call(adCode, isValid, transactionId, rewardName, rewardAmount); subscription?.cancel(); }, ); subscription = Stream.empty().listen(null); return subscription; } ``` -------------------------------- ### onShow Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-callback.md Example of using the onShow callback to log ad loaded events. ```dart callBack: GTAdsCallBack( onShow: (code) { print("Ad from ${code.alias} is now visible"); // Update UI to show ad metrics analyticsService.logAdLoaded(code.alias); }, ) ``` -------------------------------- ### Adding Ad Providers Source: https://github.com/gstory0404/gtads/blob/master/gtads/README.md This snippet demonstrates how to add, remove, and get ad providers. It shows examples for adding a single provider, a list of providers, and specifies the parameters for GTAdsCsjProvider (alias, androidId, iosId, appName). It also mentions checking provider-specific documentation for parameter details and how to handle external ad ID groups. ```dart //添加Provider GTAds.addProvider(GTAdsCsjProvider("csj","5098580","5098580",appName: "unionad")); //添加Provider列表 GTAds.addProviders([GTAdsCsjProvider("csj","5098580","5098580",appName: "unionad")]); //移除Provider GTAds.removeProvider("csj"); //获取Provider GTAds.getProvider("csj"); ``` -------------------------------- ### addProviders Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-manager.md Example of how to use the addProviders method to register CSJ and YLH ad providers. ```dart GTAdsManager.instance.addProviders([ GTAdsCsjProvider("csj", "5098580", "5098580", appName: "MyApp"), GTAdsYlhProvider("ylh", "1234567890", "1234567890"), ]); ``` -------------------------------- ### onClick Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-callback.md Example of using the onClick callback to log ad clicks. ```dart callBack: GTAdsCallBack( onClick: (code) { print("User clicked ad from ${code.alias}"); analyticsService.logAdClick(code.alias); }, ) ``` -------------------------------- ### Splash Ad Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-widgets.md Example usage of the GTAdsSplashWidget. ```dart GTAdsSplashWidget( codes: [ GTAdsCode(alias: "csj", probability: 5, androidId: "887367774", iosId: "887367774"), GTAdsCode(alias: "ylh", probability: 3, androidId: "5555555555", iosId: "6666666666"), ], width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height, timeout: 5, model: GTAdsModel.RANDOM, callBack: GTAdsCallBack( onShow: (code) { print("Splash ad displayed"); }, onFail: (code, message) { print("Splash ad failed: $message"); Navigator.pop(context); }, onClose: (code) { print("Splash ad closed"); Navigator.pop(context); }, onTimeout: () { print("Splash ad timed out"); Navigator.pop(context); }, onEnd: () { print("All splash ads failed"); Navigator.pop(context); }, ), ) ``` -------------------------------- ### Initialization Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/configuration.md Demonstrates the correct way to initialize GTAds before running the application, contrasting it with an incorrect approach. ```dart // GOOD: Initialize first void main() async { GTAds.addProviders([...]); await GTAds.init(); runApp(MyApp()); } // AVOID: Using ads before init void main() { GTAds.addProviders([...]); runApp(MyApp()); // init() not called } ``` -------------------------------- ### removeProvider Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads.md Example of removing an ad provider by its alias. ```dart // Remove the ByteDance provider GTAds.removeProvider("csj"); // Remove all providers GTAds.removeProvider("ylh"); GTAds.removeProvider("sigmob"); ``` -------------------------------- ### GTAdsNativeWidget Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-widgets.md Example usage of the GTAdsNativeWidget. ```dart GTAdsNativeWidget( codes: [ GTAdsCode(alias: "csj", probability: 5, androidId: "945417699", iosId: "945417699"), GTAdsCode(alias: "ylh", probability: 3, androidId: "9876543210", iosId: "1234567890"), ], width: 300, height: 200, timeout: 5, model: GTAdsModel.PRIORITY, callBack: GTAdsCallBack( onShow: (code) { print("Native ad displayed from ${code.alias}"); setState(() => isNativeAdVisible = true); }, onFail: (code, message) => print("Native ad failed: $message"), onClick: (code) => analyticsService.trackAdClick(code.alias), onClose: (code) => setState(() => isNativeAdVisible = false), ), ) ``` -------------------------------- ### onTimeout Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-callback.md Example demonstrating how to handle ad loading timeouts with a specified duration. ```dart await GTAds.insertAd( codes: [...], timeout: 5, callBack: GTAdsCallBack( onTimeout: () { print("No ad loaded within 5 seconds, continuing"); navigationService.goToNextScreen(); }, ), ) ``` -------------------------------- ### GTAdsBannerWidget Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-widgets.md Example usage of the GTAdsBannerWidget. ```dart GTAdsBannerWidget( codes: [ GTAdsCode(alias: "csj", probability: 5, androidId: "945410197", iosId: "945410197"), GTAdsCode(alias: "ylh", probability: 3, androidId: "8042711873318113", iosId: "5004358713683949"), ], width: 300, height: 400, timeout: 5, model: GTAdsModel.RANDOM, callBack: GTAdsCallBack( onShow: (code) => print("Banner displayed"), onFail: (code, message) => print("Banner failed: $message"), onClose: (code) => print("Banner closed"), onTimeout: () => print("Banner timed out"), onEnd: () => print("All banners failed"), ), ) ``` -------------------------------- ### Example insertAd Implementation Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-provider.md An example implementation of the insertAd function, demonstrating loading and showing an interstitial ad. ```dart @override StreamSubscription? insertAd( GTAdsCode adCode, bool isFull, GTAdsCallBack? callBack ) { // Return null if we can't proceed if (adCode.androidId == null && adCode.iosId == null) { return null; } StreamSubscription? subscription; MyAdNetwork.loadInterstitialAd( androidAdId: adCode.androidId ?? "", iosAdId: adCode.iosId ?? "", isFullScreen: isFull, onLoaded: () { callBack?.onShow?.call(adCode); MyAdNetwork.showInterstitialAd(); }, onFailed: (error) { callBack?.onFail?.call(adCode, error); subscription?.cancel(); }, onClicked: () => callBack?.onClick?.call(adCode), onClosed: () { callBack?.onClose?.call(adCode); subscription?.cancel(); }, ); // Return a dummy subscription that the framework can cancel if needed subscription = Stream.empty().listen(null); return subscription; } ``` -------------------------------- ### Example Usage of getAlias Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-provider.md An example demonstrating how to retrieve and print the alias of a GTAds provider. ```dart final provider = GTAds.getProvider("csj"); if (provider != null) { print("Provider alias: ${provider.getAlias()}"); } ``` -------------------------------- ### GTAdsCsjProvider Configuration Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/configuration.md Example of configuring GTAdsCsjProvider with privacy settings. ```dart final csjProvider = GTAdsCsjProvider( "csj", androidId: "5098580", iosId: "5098580", appName: "MyAwesomeGame", useMediation: true, androidPrivacy: AndroidPrivacy( allowPersonalAds: true, ), iosPrivacy: IOSPrivacy( allowPersonalAds: true, ), ); GTAds.addProvider(csjProvider); ``` -------------------------------- ### Error Handling Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-full-screen-ads.md A robust example of showing an ad safely, including try-catch blocks and comprehensive callback handling for various ad states. ```dart Future showAdSafely() async { try { final success = await GTAds.insertAd( codes: adCodes, timeout: 5, callBack: GTAdsCallBack( onShow: (_) => handleAdShown(), onClose: (_) => handleAdClosed(), onTimeout: () => handleAdTimeout(), onEnd: () => handleAllAdsFailed(), onFail: (_, msg) => handleAdFailure(msg), ), ); if (!success) { print("Ad loading could not start"); return false; } return true; } catch (e) { print("Error showing ad: $e"); return false; } } ``` -------------------------------- ### Best Practice 3: Handle all failure cases Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-full-screen-ads.md Shows a comprehensive example of handling ad callbacks, including success, failure, timeout, end, and close events. ```dart // GOOD: All paths handled await GTAds.insertAd( codes: codes, timeout: 5, callBack: GTAdsCallBack( onShow: (code) => print("Ad shown"), onFail: (code, msg) => print("Ad failed"), onTimeout: () => continueGame(), onEnd: () => continueGame(), onClose: (code) => continueGame(), ), ); // AVOID: Missing callbacks await GTAds.insertAd( codes: codes, timeout: 5, callBack: GTAdsCallBack( onClose: (code) => continueGame(), // Missing timeout, end, fail handlers ), ); ``` -------------------------------- ### initAd Example Implementation Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-provider.md Example implementation of the initAd method for a custom ad provider. ```dart class MyAdProvider extends GTAdsProvider { @override Future initAd(bool isDebug) async { try { await MyAdNetwork.initialize( androidAppId: androidId ?? "", iosAppId: iosId ?? "", debugMode: isDebug, ); return true; } catch (e) { print("Failed to initialize: $e"); return false; } } } ``` -------------------------------- ### onFail Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-callback.md Example of using the onFail callback to log ad provider errors. ```dart callBack: GTAdsCallBack( onFail: (code, message) { print("Ad ${code?.alias} failed: $message"); // Log failed ad provider logger.logAdError(code?.alias, message); }, ) ``` -------------------------------- ### onExpand Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-callback.md Example illustrating how to handle provider-specific events or extended functionality using the onExpand callback. ```dart callBack: GTAdsCallBack( onExpand: (code, param) { if (code.alias == "csj") { // Handle ByteDance-specific event print("CSJ event: $param"); } else if (code.alias == "ylh") { // Handle Tencent-specific event print("YLH event: $param"); } }, ) ``` -------------------------------- ### onEnd Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-callback.md Example showing how to handle the scenario where all ad placements in a fallback list fail to load. ```dart callBack: GTAdsCallBack( onEnd: () { print("All ads in the fallback list failed"); // Show a fallback UI or default content uiService.showDefaultContent(); }, ) ``` -------------------------------- ### bannerAd Example Implementation Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-provider.md Example implementation of the bannerAd method for a custom ad provider. ```dart @override Widget? bannerAd( GTAdsCode adCode, double width, double height, GTAdsCallBack? callBack ) { if (adCode.androidId == null && adCode.iosId == null) { return null; } return MyAdNetworkBannerView( androidAdId: adCode.androidId ?? "", iosAdId: adCode.iosId ?? "", width: width, height: height, onAdLoaded: () => callBack?.onShow?.call(adCode), onAdFailed: (error) => callBack?.onFail?.call(adCode, error), onAdClicked: () => callBack?.onClick?.call(adCode), onAdClosed: () => callBack?.onClose?.call(adCode), ); } ``` -------------------------------- ### Example splashAd Implementation Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-provider.md An example implementation of the splashAd function using a hypothetical MyAdNetworkSplashView. ```dart @override Widget? splashAd( GTAdsCode adCode, double width, double height, GTAdsCallBack? callBack ) { return MyAdNetworkSplashView( androidAdId: adCode.androidId ?? "", iosAdId: adCode.iosId ?? "", width: width, height: height, onAdLoaded: () => callBack?.onShow?.call(adCode), onAdFailed: (error) => callBack?.onFail?.call(adCode, error), onAdClicked: () => callBack?.onClick?.call(adCode), onAdClosed: () => callBack?.onClose?.call(adCode), ); } ``` -------------------------------- ### Conditional Provider Registration Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-manager.md An example demonstrating how to conditionally register ad providers based on app state or remote configuration. ```dart Future setupAdProviders() async { final providers = []; // Always add CSJ providers.add(GTAdsCsjProvider( "csj", androidId: "5098580", iosId: "5098580", appName: "MyApp" )); // Add YLH only if user is in specific region if (isAsiaUser()) { providers.add(GTAdsYlhProvider( "ylh", androidId: "1234567890", iosId: "1234567890" )); } // Add Sigmob only if enabled in remote config if (await remoteConfig.isSigmobEnabled()) { providers.add(GTAdsSigmobProvider( "sigmob", androidId: "9876543210", iosId: "9876543210" )); } GTAdsManager.instance.addProviders(providers); await GTAds.init(); } ``` -------------------------------- ### Use meaningful aliases Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/configuration.md Example demonstrating the use of clear and descriptive aliases for providers. ```dart // GOOD: Clear provider names GTAdsCsjProvider("bytedance", androidId: "...", iosId: "...", appName: "..."), GTAdsYlhProvider("tencent", androidId: "...", iosId: "..."), // AVOID: Cryptic names GTAdsCsjProvider("ad1", androidId: "...", iosId: "...", appName: "..."), GTAdsYlhProvider("ad2", androidId: "...", iosId: "..."), ``` -------------------------------- ### Example nativeAd Implementation Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-provider.md An example implementation of the nativeAd function using a hypothetical MyAdNetworkNativeView. ```dart @override Widget? nativeAd( GTAdsCode adCode, double width, double height, GTAdsCallBack? callBack ) { return MyAdNetworkNativeView( androidAdId: adCode.androidId ?? "", iosAdId: adCode.iosId ?? "", width: width, height: height, onAdLoaded: () => callBack?.onShow?.call(adCode), onAdFailed: (error) => callBack?.onFail?.call(adCode, error), onAdClicked: () => callBack?.onClick?.call(adCode), ); } ``` -------------------------------- ### onClose Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-callback.md Example of using the onClose callback to resume game or music after an ad is closed. ```dart callBack: GTAdsCallBack( onClose: (code) { print("User closed ad from ${code.alias}"); // Resume game, resume music, etc. gameService.resume(); }, ) ``` -------------------------------- ### Reward Ad Callback Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-callback.md Example demonstrating the usage of GTAds.rewardAd with various callback events, including verification. ```dart await GTAds.rewardAd( codes: [ GTAdsCode(alias: "csj", probability: 5, androidId: "945418088", iosId: "945418088"), ], rewardName: "Gold", rewardAmount: 100, userId: "user123", customData: "daily_chest", timeout: 10, callBack: GTAdsCallBack( onShow: (code) { print("Reward ad displayed"); gameService.pauseGame(); }, onFail: (code, message) { print("Reward ad failed: $message"); }, onFinish: (code) { print("User completed the video"); }, onVerify: (code, verify, transId, rewardName, rewardAmount) { if (verify) { print("Verified! Granting $rewardAmount $rewardName"); playerService.addReward(transId, rewardName, rewardAmount); } else { print("Verification failed, reward not granted"); } }, onClose: (code) { print("Reward ad closed"); gameService.resumeGame(); }, onExpand: (code, param) { print("Extended callback: $param"); }, onTimeout: () { print("Reward ad timed out"); gameService.resumeGame(); }, onEnd: () { print("All reward ads exhausted"); }, ), ); ``` -------------------------------- ### Error Fallback UI Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-widgets.md Example of showing a fallback UI when an ad fails to load. ```dart class AdContainer extends StatefulWidget { @override State createState() => _AdContainerState(); } class _AdContainerState extends State { bool adLoaded = false; bool adFailed = false; @override Widget build(BuildContext context) { if (adFailed) { return Container( height: 250, color: Colors.grey[200], child: Center( child: Text("Ad failed to load"), ), ); } return GTAdsBannerWidget( codes: adCodes, width: 300, height: 250, timeout: 5, callBack: GTAdsCallBack( onShow: (code) => setState(() => adLoaded = true), onEnd: () => setState(() => adFailed = true), ), ); } } ``` -------------------------------- ### Ad Placement in Lists Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-widgets.md Example of embedding an ad within a ListView. ```dart ListView( children: [ // Content ContentWidget(), // Ad at specific position SizedBox( width: double.infinity, child: GTAdsBannerWidget( codes: adCodes, width: 300, height: 250, timeout: 5, ), ), // More content ContentWidget(), ], ) ``` -------------------------------- ### Baidu Baiqingteng (BQT) Provider Configuration Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/configuration.md Example of configuring and adding a Baidu Baiqingteng ad provider. ```dart final bqtProvider = GTAdsBqtProvider( "bqt", androidId: "123456", iosId: "123456", ); GTAds.addProvider(bqtProvider); ``` -------------------------------- ### rewardAd Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads.md Example usage of the rewardAd function to load and display a reward video ad. ```dart final success = await GTAds.rewardAd( codes: [ GTAdsCode(alias: "csj", probability: 5, androidId: "945418088", iosId: "945418088"), GTAdsCode(alias: "ylh", probability: 3, androidId: "9876543210", iosId: "1234567890"), ], rewardName: "100 Gold Coins", rewardAmount: 100, userId: "user123", customData: "level_5_chest", timeout: 10, model: GTAdsModel.PRIORITY, callBack: GTAdsCallBack( onShow: (code) => print("Reward ad shown: ${code.alias}"), onVerify: (code, verify, transId, rewardName, rewardAmount) { if (verify) { print("Reward verified! Grant $rewardAmount $rewardName"); } }, onFail: (code, message) => print("Reward ad failed: $message"), onClick: (code) => print("Reward ad clicked"), onClose: (code) => print("Reward ad closed"), onTimeout: () => print("Reward ad loading timed out"), onEnd: () => print("All reward ads failed to load"), ), ); if (success) { print("Reward ad loading started"); } ``` -------------------------------- ### onVerify Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-callback.md Example of using the onVerify callback to grant rewards based on verification status. ```dart callBack: GTAdsCallBack( onVerify: (code, verify, transId, rewardName, rewardAmount) { if (verify) { print("Verified: Grant $rewardAmount $rewardName to user"); playerService.addReward(transId, rewardName, rewardAmount); } else { print("Reward verification failed"); } }, ) ``` -------------------------------- ### Conditional Rendering Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-widgets.md Example of conditionally rendering an ad based on a boolean flag. ```dart bool showAds = true; // Load from user preferences if (showAds) { GTAdsBannerWidget( codes: adCodes, width: 300, height: 400, timeout: 5, callBack: GTAdsCallBack( onShow: (code) => setState(() => hasAdDisplayed = true), onEnd: () => setState(() => hasAdDisplayed = false), ), ) } else { SizedBox.shrink() // Empty widget } ``` -------------------------------- ### Sigmob Provider Configuration Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/configuration.md Example of configuring and adding a Sigmob ad provider. ```dart final sigmobProvider = GTAdsSigmobProvider( "sigmob", androidId: "9876543210", iosId: "9876543210", ); GTAds.addProvider(sigmobProvider); ``` -------------------------------- ### Native Ad Source: https://github.com/gstory0404/gtads/blob/master/gtads/README.md Example of how to implement a native ad. ```dart GTAdsNativeWidget( //需要的广告位组 codes: [GTAdsCode(alias: "csj", probability: 5,androidId: "945417699",iosId: "945417699")], width: 300, height: 200, //超时时间 当广告失败后会依次重试其他广告 直至所有广告均加载失败 设置超时时间可提前取消 timeout: 5, //广告加载模式 [GTAdsModel.PRIORITY]优先级模式 [GTAdsModel.RANDOM]随机模式 //默认随机模式 model: GTAdsModel.RANDOM, callBack: GTAdsCallBack( onShow: (code) { print("信息流显示 ${code.toJson()}"); }, onClick: (code) { print("信息流点击 ${code.toJson()}"); }, onFail: (code,message) { print("信息流错误 ${code.toJson()} $message"); }, onClose: (code) { print("信息流关闭 ${code.toJson()}"); }, onTimeout: () { print("信息流加载超时"); }, onEnd: () { print("信息流所有广告位都加载失败"); }, ), ), ``` -------------------------------- ### Multiple Ad Positions Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-widgets.md Example demonstrating multiple ad types and positions within a layout. ```dart Column( children: [ // Top banner GTAdsBannerWidget( codes: bannerCodes, width: 320, height: 50, timeout: 5, ), Expanded( child: ListView( children: [ // List content with embedded native ads ListTile(title: Text("Item 1")), ListTile(title: Text("Item 2")), GTAdsNativeWidget( codes: nativeCodes, width: 320, height: 200, timeout: 5, ), ListTile(title: Text("Item 3")), ], ), ), ], ) ``` -------------------------------- ### Future>> Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/types.md Example of the return type for GTAds.init(). ```dart List> ``` ```dart [ {"csj": true}, {"ylh": true}, {"sigmob": false} ] ``` -------------------------------- ### Example Usage Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads-code.md Demonstrates how to create GTAdsCode instances and use them in a GTAdsBannerWidget. ```dart // Create ad codes for different providers final csjBanner = GTAdsCode( alias: "csj", androidId: "945410197", iosId: "945410197", probability: 5 ); final ylhBanner = GTAdsCode( alias: "ylh", androidId: "8042711873318113", iosId: "5004358713683949", probability: 3 ); // Use in ad widget GTAdsBannerWidget( codes: [csjBanner, ylhBanner], width: 300, height: 400, timeout: 5, ) ``` -------------------------------- ### GTAdsCallBack Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/README.md Demonstrates the structure and available callbacks for GTAds. ```dart GTAdsCallBack( onShow: (code) { // Ad loaded and visible }, onFail: (code, msg) { // Single ad failed (auto-retries next) }, onClick: (code) { // User clicked ad }, onFinish: (code) { // Video finished playing }, onVerify: (code, verify, transId, name, amount) { // Reward verification result }, onClose: (code) { // Ad dismissed/closed }, onExpand: (code, param) { // Provider-specific extended callback }, onTimeout: () { // Loading exceeded timeout }, onEnd: () { // All ads exhausted }, ) ``` -------------------------------- ### Reward Ad Source: https://github.com/gstory0404/gtads/blob/master/gtads/README.md Example of how to implement a reward ad. ```dart var b = await GTAds.rewardAd( //需要的广告位数组 codes: [GTAdsCode(alias: "csj", probability: 5,androidId: "945418088",iosId: "945418088")], //奖励名称 rewardName: "100金币", //奖励数量 rewardAmount: 100, //用户id userId: "user100", //扩展参数 customData: "123", //超时时间 当广告失败后会依次重试其他广告 直至所有广告均加载失败 设置超时时间可提前取消 timeout: 5, //广告加载模式 [GTAdsModel.RANDOM]优先级模式 [GTAdsModel.RANDOM]随机模式 //默认随机模式 model: GTAdsModel.RANDOM, callBack: GTAdsCallBack( onShow: (code) { print("激励广告显示 ${code.toJson()}"); }, onFail: (code, message) { print("激励广告失败 ${code.toJson()} $message"); }, onClick: (code) { print("激励广告点击 ${code.toJson()}"); }, onClose: (code) { print("激励广告关闭 ${code.toJson()}"); }, onVerify: (code, verify, transId, rewardName, rewardAmount) { print( "激励广告关闭 ${code.toJson()} $verify $transId $rewardName $rewardAmount"); }, onExpand: (code, param) { print("激励广告自定义参数 ${code.toJson()} $param"); }, onTimeout: () { print("激励广告加载超时"); }, onEnd: () { print("激励广告所有广告位都加载失败"); }, ), ); if (b) { print("激励广告开始请求"); }else{ print("激励广告开始请求失败"); } ``` -------------------------------- ### insertAd Example Source: https://github.com/gstory0404/gtads/blob/master/_autodocs/api-reference/gtads.md Example usage of the insertAd function to load and display an interstitial ad. ```dart await GTAds.insertAd( codes: [ GTAdsCode(alias: "csj", probability: 5, androidId: "946201351", iosId: "946201351"), GTAdsCode(alias: "ylh", probability: 3, androidId: "8042711873318113", iosId: "5004358713683949"), ], isFull: false, timeout: 5, model: GTAdsModel.RANDOM, callBack: GTAdsCallBack( onShow: (code) => print("Ad shown: ${code.alias}"), onFail: (code, message) => print("Ad failed: $message"), onClick: (code) => print("Ad clicked"), onClose: (code) => print("Ad closed"), onTimeout: () => print("Ad loading timed out"), onEnd: () => print("All ads failed to load"), ), ); ```