Flutter原生广告集成插件native_ads_flutter的使用

Flutter原生广告集成插件native_ads_flutter的使用

作者

PRAGNESH

开始前

  • ✔️ Native Ads Android
  • ✔️ Native Ads IOS
  • ✔️ Native Ads Banner
  • ✔️ Native Ads Full

注意: AdMOB仅支持移动设备上的广告。Web和桌面不在支持范围内。

  • ✔️ Android
  • ✔️ iOS

使用前的准备

在你的项目中引入native_ads_flutter包:

dependencies:
    native_ads_flutter: "<LATEST_VERSION>"

安装依赖:

flutter pub get

Android 特定设置

更新你的 AndroidManifest.xml 文件中的广告应用ID

Android: ca-app-pub-3940256099942544~3347511713
iOS: ca-app-pub-3940256099942544~1458002511

AndroidManifest.xml文件中添加以下内容:

<manifest>
  <application>
    <meta-data
        android:name="com.google.android.gms.ads.APPLICATION_ID"
        android:value="ca-app-pub-3940256099942544~3347511713"/>
    </application>
</manifest>

iOS 特定设置

更新你的 Info.plist 文件

Info.plist文件中添加以下内容:

<key>GADApplicationIdentifier</key>
<string>ca-app-pub-3940256099942544~1458002511</string>
<key>io.flutter.embedded_views_preview</key>
<true/>

创建控制器

创建一个NativeAdmobController实例来控制广告的加载和显示:

final _controller = NativeAdmobController();

显示原生广告

在你的应用中添加以下代码来显示原生广告:

Container(
  height: 330,
  child: NativeAdmob(
    adUnitID: "<Your ad unit ID>",
    loading: Center(child: CircularProgressIndicator()), // 加载时的指示器
    error: Text("Failed to load the ad"), // 广告加载失败时的提示信息
    controller: _controller,
    type: NativeAdmobType.full, // 广告类型,这里使用全屏类型
    options: NativeAdmobOptions(
      ratingColor: Colors.green, // 设置评分的颜色
      // 其他选项...
    ),
  )
)

更多关于Flutter原生广告集成插件native_ads_flutter的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter原生广告集成插件native_ads_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter应用中集成和使用native_ads_flutter插件的一个示例代码案例。这个插件允许你在Flutter应用中展示原生广告,比如Google AdMob的原生广告。

步骤 1: 添加依赖

首先,你需要在pubspec.yaml文件中添加native_ads_flutter依赖:

dependencies:
  flutter:
    sdk: flutter
  native_ads_flutter: ^x.y.z  # 请替换为最新版本号

然后运行flutter pub get来安装依赖。

步骤 2: 配置AdMob

在你的android/app/src/main/AndroidManifest.xml文件中添加AdMob的元数据:

<meta-data
    android:name="com.google.android.gms.ads.APPLICATION_ID"
    android:value="ca-app-pub-xxxxxxxxxxxxxxxx~xxxxxxxxxx"/>

ca-app-pub-xxxxxxxxxxxxxxxx~xxxxxxxxxx替换为你的AdMob应用ID。

对于iOS,你需要在ios/Runner/Info.plist中添加AdMob的配置。

步骤 3: 初始化广告

在你的Flutter应用的入口文件(通常是main.dart)中初始化广告:

import 'package:flutter/material.dart';
import 'package:native_ads_flutter/native_ads_flutter.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  // 初始化NativeAds
  NativeAd.init(
    adUnitId: 'ca-app-pub-xxxxxxxxxxxxxxxx/xxxxxxxxxx',  // 替换为你的AdMob原生广告单元ID
    factoryId: 'adFactoryExample',
    testDevices: <String>[], // 测试设备ID列表,例如 ['EMULATOR_ID', 'YOUR_DEVICE_ID'], 在发布时移除
    directionality: TextDirection.ltr,
    requestOptions: RequestOptions(
      contentUrl: Uri.parse('https://www.example.com'),
      keywords: <String>['foo', 'bar'],
    ),
  );

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

步骤 4: 展示原生广告

在你的页面或组件中展示原生广告:

import 'package:flutter/material.dart';
import 'package:native_ads_flutter/native_ads_flutter.dart';

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  NativeAd? _nativeAd;

  @override
  void initState() {
    super.initState();
    _loadNativeAd();
  }

  Future<void> _loadNativeAd() async {
    _nativeAd = await NativeAd.load(
      adUnitId: 'ca-app-pub-xxxxxxxxxxxxxxxx/xxxxxxxxxx', // 替换为你的AdMob原生广告单元ID
      factoryId: 'adFactoryExample',
      targetingInfo: TargetingInfo(
        keywords: <String>['foo', 'bar'],
        contentUrl: Uri.parse('https://www.example.com'),
        childDirected: false,
        nonPersonalizedAdsOnly: false,
      ),
    );

    if (mounted) {
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Native Ad Example'),
      ),
      body: Center(
        child: _nativeAd == null
            ? CircularProgressIndicator()
            : Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Image.network(_nativeAd!.images!.leadImage!.url),
                  Text(
                    _nativeAd!.headline!,
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  Text(_nativeAd!.body!),
                  SizedBox(height: 16),
                  ElevatedButton(
                    onPressed: () => _nativeAd!.callToAction!.url != null
                        ? _launchUrl(_nativeAd!.callToAction!.url!)
                        : null,
                    child: Text(_nativeAd!.callToAction!.text ?? 'Call to Action'),
                  ),
                ],
              ),
      ),
    );
  }

  Future<void> _launchUrl(Uri url) async {
    if (await canLaunchUrl(url)) {
      await launchUrl(url);
    } else {
      throw 'Could not launch $url';
    }
  }
}

在这个示例中,我们展示了如何加载和显示一个原生广告,包括广告的图片、标题、正文和行动号召按钮。

请确保你已经正确配置了AdMob,并且你的AdMob账号中有相应的广告单元。同时,注意在实际应用中处理广告加载失败的情况,并遵守相关的广告政策。

回到顶部