【问题标题】:Adding Unity Ads in flutter application在 flutter 应用程序中添加 Unity Ads
【发布时间】:2023-02-04 01:59:25
【问题描述】:

你好堆栈溢出社区。

我正在尝试在我的 flutter 应用程序中设置统一广告,但无法正常工作。 我在 Internet 上只找到示例,这些示例显示了如何通过按钮和点击事件实现广告,但没有显示如何在不触发事件的情况下显示广告。

我想要一个在应用启动后可见的横幅广告,以及一个在应用启动后显示的插页式广告 但它没有按预期工作。插页式广告仅在热重载后弹出,但在通过我的测试设备手动输入应用程序后不会弹出。

这是我的代码:

import 'package:kalendar/ad_helper.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:unity_ads_plugin/unity_ads_plugin.dart';

    void main() async {
      await  WidgetsFlutterBinding.ensureInitialized();

      await UnityAds.init(
        gameId: AdHelper.addUnitId,
        onComplete: () => print('Initialization Complete'),
        onFailed: (error, message) =>
            print('Initialization Failed: $error $message'),
      );

      await UnityAds.load(
        placementId: AdHelper.interstitialId,
        onComplete: (placementId) => print('Load Complete $placementId'),
        onFailed: (placementId, error, message) =>
            print('Load Failed $placementId: $error $message'),
      );

      await UnityBannerAd(
        placementId: AdHelper.bannerId,
        onLoad: (placementId) => print('Banner loaded: $placementId'),
        onClick: (placementId) => print('Banner clicked: $placementId'),
        onFailed: (placementId, error, message) =>
            print('Banner Ad $placementId failed: $error $message'),
      );

      await 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'),
        onComplete: (placementId) =>
            print('Video Ad $placementId completed'),
        onFailed: (placementId, error, message) =>
            print('Video Ad $placementId failed: $error $message'),
      );
         runApp(MyApp());
    }

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Kalendar',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: PageViewDemo(),
    );
  }
}

class PageViewDemo extends StatefulWidget {
  @override
  _PageViewDemoState createState() => _PageViewDemoState();
}

class _PageViewDemoState extends State<PageViewDemo> {
  PageController _controller = PageController(
    initialPage: 0,
  );

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  final List images = [
  "https://google.com",
  "https://google.com",
  "https://google.com",
  "https://google.com",

  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: SizedBox.fromSize(
            size: const Size.fromHeight(648),
            child: PageView.builder(
              allowImplicitScrolling: true,
              controller: PageController(viewportFraction: 1),
              itemCount: images.length,
              itemBuilder: (BuildContext context, int index) {
                return Padding(
                  padding: const EdgeInsets.symmetric(
                    vertical: 0,
                    horizontal: 0,
                  ),
                  child: Material(
                    elevation: 5,
                    borderRadius: BorderRadius.circular(1),
                    child: Stack(
                      fit: StackFit.expand,
                      children: [
                        Image.network(
                          images[index],
                          fit: BoxFit.contain,
                        ),
                        DecoratedBox(
                          decoration: BoxDecoration(
                            gradient: LinearGradient(
                              begin: FractionalOffset.bottomCenter,
                              end: FractionalOffset.topCenter,
                              colors: [
                                const Color(0x00000000).withOpacity(0.0),
                                const Color(0xff000000).withOpacity(0.01),

                              ],
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                );
              },
            ),
          )),
    );
  }
}



class AdHelper {
  static String get addUnitId {
    if (defaultTargetPlatform == TargetPlatform.android) {
      return '4828341';
    }
    if (defaultTargetPlatform == TargetPlatform.iOS) {
      return '4828340';
    }
    return '';
  }

  static String get bannerId {
    if (defaultTargetPlatform == TargetPlatform.android) {
      return 'Banner_Android';
    }
    if (defaultTargetPlatform == TargetPlatform.iOS) {
      return 'Banner_iOS';
    }
    return '';
  }

  static String get interstitialId {
    if (defaultTargetPlatform == TargetPlatform.android) {
      return 'Interstitial_Android';
    }
    if (defaultTargetPlatform == TargetPlatform.iOS) {
      return 'Interstitial_iOS';
    }
    return '';
  }

【问题讨论】:

    标签: android ios flutter unity3d ads


    【解决方案1】:

    首先创建一个飞镖文件'unityAds.dart','unityAds.dart'的代码是:

        import 'package:flutter/foundation.dart';
        import 'package:unity_ads_plugin/unity_ads_plugin.dart';
        
        class AdManager {
        
          static Future<void> loadUnityIntAd() async {
            await UnityAds.load(
              placementId: AdHelper.interstitialId,
              onComplete: (placementId) => print('Load Complete $placementId'),
              onFailed: (placementId, error, message) =>
                  print('Load Failed $placementId: $error $message'),
            );
          }
        
          static Future<void> showIntAd() async {
            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'),
                onComplete: (placementId) async {
                  await loadUnityIntAd();
                },
                onFailed: (placementId, error, message) async {
                  await loadUnityIntAd();
                });
          }
        
          static Future<void> loadUnityRewardedAd() async {
            await UnityAds.load(
              placementId: AdHelper.rewardedId,
              onComplete: (placementId) => print('Load Complete $placementId'),
              onFailed: (placementId, error, message) =>
                  print('Load Failed $placementId: $error $message'),
            );
          }
        
          static Future<void> showRewardedAd() async {
            UnityAds.showVideoAd(
                placementId: AdHelper.rewardedId,
                onStart: (placementId) => print('Video Ad $placementId started'),
                onClick: (placementId) => print('Video Ad $placementId click'),
                onSkipped: (placementId) => print('Video Ad $placementId skipped'),
                onComplete: (placementId) async {
                  await loadUnityRewardedAd();
                },
                onFailed: (placementId, error, message) async {
                  await loadUnityRewardedAd();
                });
          }
        }
        
        class AdHelper {
          static String get addUnitId {
            if (defaultTargetPlatform == TargetPlatform.android) {
              return '4994515';
            }
            if (defaultTargetPlatform == TargetPlatform.iOS) {
              return '4994514';
            }
            return '';
          }
        
          static String get bannerId {
            if (defaultTargetPlatform == TargetPlatform.android) {
              return 'Banner_Android';
            }
            if (defaultTargetPlatform == TargetPlatform.iOS) {
              return 'Banner_iOS';
            }
            return '';
          }
        
          static String get interstitialId {
            if (defaultTargetPlatform == TargetPlatform.android) {
              return 'Interstitial_Android';
            }
            if (defaultTargetPlatform == TargetPlatform.iOS) {
              return 'Interstitial_iOS';
            }
            return '';
          }
        
        
          static String get rewardedId {
            if (defaultTargetPlatform == TargetPlatform.android) {
              return 'Rewarded_Android';
            }
            if (defaultTargetPlatform == TargetPlatform.iOS) {
              return 'Rewarded_iOS';
            }
            return '';
          }
        }
    

    现在你在 'main.dart' 上添加代码:

    import 'package:demo_01/unityAds.dart';
    import 'package:flutter/material.dart';
    import 'package:unity_ads_plugin/unity_ads_plugin.dart';
    
    Future<void> main() async {
    
      WidgetsFlutterBinding.ensureInitialized();
      await UnityAds.init(
        // gameId: '5041608',
        gameId: AdHelper.addUnitId,
        onComplete: () => print('Initialization Complete'),
        onFailed: (error, message) =>
            print('Initialization Failed: $error $message'),
      );
    
     
    
      runApp(MaterialApp(
        debugShowCheckedModeBanner: false,
        home: const MyLogin(),
        routes: {
          'login': (context) => const MyLogin(),
        },
      ));
    }
    

    现在,您可以在哪里实现添加:

    
    ....
    
    class _MyLoginState extends State<MyLogin> {
    
      @override
      void initState() {
        super.initState();
        WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
          await AdManager.loadUnityIntAd();
          await AdManager.loadUnityRewardedAd();
        });
      }
    
    ....
    }
    
    

    现在你在 onTap 选项上添加这段代码:

     onTap: () async {
         await AdManager.showRewardedAd();
     }
    

    【讨论】:

      猜你喜欢
      • 2019-06-05
      • 2019-04-02
      • 2019-07-29
      • 1970-01-01
      • 2018-08-31
      • 1970-01-01
      • 2020-10-11
      • 1970-01-01
      相关资源
      最近更新 更多