You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中onPressed调用Future<void>函数展示Unity广告遇问题求助

Flutter调用Unity插屏广告问题解决方案

核心问题分析

你的showIntAd虽然声明为Future<void>,但内部调用的UnityAds.showVideoAd是基于回调的异步操作,当前代码没有正确让Future等待广告播放流程完成,同时缺少广告就绪状态检查,容易导致调用失败。

修复方案

1. 用Completer包装回调,让Future正确等待广告流程

将回调式的广告操作包装成Future,确保await AdManager.showIntAd()能等待广告播放完成/失败后再继续执行。

2. 增加广告就绪检查

调用广告前先检查是否已加载完成,未加载则先触发加载,避免直接调用未就绪的广告。

修改后的完整代码

AdManager.dart

import 'dart:async';
import 'package:unity_ads_plugin/unity_ads_plugin.dart';

class AdManager {
  static Future<void> loadUnityIntAd() async {
    await UnityAds.load(placementId: AdHelper.interstitialId);
  }

  static Future<void> showIntAd() async {
    // 检查广告是否就绪,未就绪则先加载
    if (!await UnityAds.isReady(AdHelper.interstitialId)) {
      await loadUnityIntAd();
      // 再次检查,仍未就绪则直接返回
      if (!await UnityAds.isReady(AdHelper.interstitialId)) {
        print("插屏广告加载失败,无法展示");
        return;
      }
    }

    final completer = Completer<void>();

    UnityAds.showVideoAd(
      placementId: AdHelper.interstitialId,
      onStart: (placementId) => print('Video Ad $placementId started'),
      onClick: (placementId) => print('Video Ad $placementId click'),
      onSkipped: (placementId) {
        print('Video Ad $placementId skipped');
        completer.complete();
        loadUnityIntAd(); // 预加载下一条广告
      },
      onComplete: (placementId) {
        print('Video Ad $placementId completed');
        completer.complete();
        loadUnityIntAd();
      },
      onFailed: (placementId, error, message) {
        print('Video Ad $placementId failed: $message');
        completer.completeError(Exception(message));
        loadUnityIntAd();
      },
    );

    return completer.future;
  }
}

class AdHelper {
  static const String interstitialId = "你的插屏广告ID"; // 替换为实际ID
}

main.dart(增加错误处理)

Align(
  alignment: Alignment.bottomCenter,
  child: Padding(
    padding: EdgeInsets.all(8.0),
    child: ElevatedButton(
      onPressed: () async {
        try {
          await AdManager.showIntAd();
          // 可选:广告播放完成后执行的逻辑
        } catch (e) {
          print("广告播放出错: $e");
        }
      },
      child: Text('Doniraj'),
    ),
  ),
)

额外注意事项

  • 确保App启动时已初始化UnityAds:
    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await UnityAds.initialize(
        gameId: "你的Unity游戏ID", // 替换为实际ID
        testMode: true, // 测试阶段开启,发布时关闭
      );
      // 预加载第一条广告
      await AdManager.loadUnityIntAd();
      runApp(MyApp());
    }
    
  • 确认placementId与Unity Ads后台配置完全一致
  • 测试设备需添加到Unity后台的测试设备列表,避免广告被限制

内容的提问来源于stack exchange,提问作者Terrence Skill

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 17:57:15