Flutter广告展示插件fastyle_ad的使用

发布于 1周前 作者 sinazl 来自 Flutter

Flutter广告展示插件fastyle_ad的使用

fastyle_ad 是一个为 fastyle 库设计的一组广告小部件。通过这些小部件,你可以轻松地在你的 Flutter 应用中集成各种类型的广告。

完整示例Demo

下面是一个完整的示例,展示了如何在 Flutter 应用中使用 fastyle_ad 插件。

// Flutter imports:
import 'package:flutter/material.dart';

// Package imports:
import 'package:fastyle_ad/fastyle_ad.dart';
import 'package:fastyle_core/fastyle_core.dart';
import 'package:go_router/go_router.dart';
import 'package:lingua_ad/generated/codegen_loader.g.dart';
import 'package:lingua_core/lingua_core.dart';
import 'package:lingua_purchases/generated/codegen_loader.g.dart';
import 'package:tbloc/tbloc.dart';

// Project imports:
import 'package:fastyle_ad_example/routes.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

final kAppInfo = kFastAppInfo.copyWith(
  appName: 'Fastyle Ads',
  databaseVersion: 0,
  supportedLocales: const [
    Locale('de'),
    Locale('en'),
    Locale('fr'),
    Locale('es'),
    Locale('it'),
    Locale('ja'),
    Locale('pt'),
    Locale('ru'),
    Locale('zh'),
  ],
);

class MyApp extends StatelessWidget with FastAdInformationJobDelegate {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return FastApp(
      appInformation: kAppInfo,
      assetLoader: LinguaLoader.withLocales(mapLocales: [
        AdCodegenLoader.mapLocales,
        PurchasesCodegenLoader.mapLocales,
      ]),
      blocProviders: [
        BlocProvider(bloc: FastAdInfoBloc()),
        BlocProvider(bloc: FastSplashAdBloc()),
        BlocProvider(bloc: FastRewardedAdBloc()),
      ],
      loaderJobs: [
        FastAdInfoJob(delegate: this),
        FastSplashAdJob(),
        FastRewardedAdJob(),
      ],
      routesForMediaType: (mediaType) => [
        ...kAppRoutes,
        GoRoute(path: '/', builder: (_, __) => const MyHomePage()),
      ],
    );
  }

  @override
  Future<FastAdInfo> onGetAdInformationModel(BuildContext context) async {
    return const FastAdInfo(
      adServiceUriAuthority: 'services.lumen.tyrcord.com',
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return FastSectionPage(
      titleText: 'Fastyle Ads Demo',
      child: FastNavigationListView(
        onSelectionChanged: (FastItem<String> item) {
          GoRouter.of(context).push('/${item.value}');
        },
        items: const [
          FastItem(labelText: 'Smart Native Ads', value: 'smart-native'),
          FastItem(labelText: 'Custom Ads', value: 'custom'),
          FastItem(labelText: 'Loading Ads', value: 'loading'),
          FastItem(labelText: 'Rewarded Ads', value: 'rewarded'),
        ],
      ),
    );
  }
}

代码解释

  1. 导入必要的库

    import 'package:flutter/material.dart';
    import 'package:fastyle_ad/fastyle_ad.dart';
    import 'package:fastyle_core/fastyle_core.dart';
    import 'package:go_router/go_router.dart';
    import 'package:lingua_ad/generated/codegen_loader.g.dart';
    import 'package:lingua_core/lingua_core.dart';
    import 'package:lingua_purchases/generated/codegen_loader.g.dart';
    import 'package:tbloc/tbloc.dart';
    
  2. 初始化应用

    void main() {
      WidgetsFlutterBinding.ensureInitialized();
      runApp(const MyApp());
    }
    
  3. 配置应用信息

    final kAppInfo = kFastAppInfo.copyWith(
      appName: 'Fastyle Ads',
      databaseVersion: 0,
      supportedLocales: const [
        Locale('de'),
        Locale('en'),
        Locale('fr'),
        Locale('es'),
        Locale('it'),
        Locale('ja'),
        Locale('pt'),
        Locale('ru'),
        Locale('zh'),
      ],
    );
    
  4. 创建应用主体

    class MyApp extends StatelessWidget with FastAdInformationJobDelegate {
      const MyApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return FastApp(
          appInformation: kAppInfo,
          assetLoader: LinguaLoader.withLocales(mapLocales: [
            AdCodegenLoader.mapLocales,
            PurchasesCodegenLoader.mapLocales,
          ]),
          blocProviders: [
            BlocProvider(bloc: FastAdInfoBloc()),
            BlocProvider(bloc: FastSplashAdBloc()),
            BlocProvider(bloc: FastRewardedAdBloc()),
          ],
          loaderJobs: [
            FastAdInfoJob(delegate: this),
            FastSplashAdJob(),
            FastRewardedAdJob(),
          ],
          routesForMediaType: (mediaType) => [
            ...kAppRoutes,
            GoRoute(path: '/', builder: (_, __) => const MyHomePage()),
          ],
        );
      }
    
      @override
      Future<FastAdInfo> onGetAdInformationModel(BuildContext context) async {
        return const FastAdInfo(
          adServiceUriAuthority: 'services.lumen.tyrcord.com',
        );
      }
    }
    
  5. 创建首页

    class MyHomePage extends StatelessWidget {
      const MyHomePage({super.key});
    
      @override
      Widget build(BuildContext context) {
        return FastSectionPage(
          titleText: 'Fastyle Ads Demo',
          child: FastNavigationListView(
            onSelectionChanged: (FastItem<String> item) {
              GoRouter.of(context).push('/${item.value}');
            },
            items: const [
              FastItem(labelText: 'Smart Native Ads', value: 'smart-native'),
              FastItem(labelText: 'Custom Ads', value: 'custom'),
              FastItem(labelText: 'Loading Ads', value: 'loading'),
              FastItem(labelText: 'Rewarded Ads', value: 'rewarded'),
            ],
          ),
        );
      }
    }
    

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

1 回复

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


当然,以下是如何在Flutter项目中集成和使用fastyle_ad插件来展示广告的示例代码。请注意,实际使用时你需要确保已经添加了fastyle_ad依赖,并配置好广告平台的必要信息。

1. 添加依赖

首先,在你的pubspec.yaml文件中添加fastyle_ad依赖:

dependencies:
  flutter:
    sdk: flutter
  fastyle_ad: ^最新版本号  # 请替换为实际的最新版本号

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

2. 配置广告平台(以AdMob为例)

确保你已经在AdMob等广告平台创建了应用并获取了必要的广告单元ID。

3. 初始化广告插件

在你的Flutter应用的入口文件(通常是main.dart)中初始化广告插件。这里以AdMob为例,但fastyle_ad可能支持多个广告平台,具体初始化方法可能有所不同。

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

void main() {
  // 初始化广告配置,这里假设使用AdMob
  AdConfiguration.initialize(
    adUnitId: '你的AdMob广告单元ID', // 替换为你的AdMob广告单元ID
    appId: '你的AdMob应用ID',        // 替换为你的AdMob应用ID
    isTesting: kDebugMode,           // 开发模式下启用测试广告
  );

  runApp(MyApp());
}

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

4. 在页面展示广告

现在你可以在任何页面中展示广告。例如,在一个名为HomeScreen的页面中展示一个横幅广告:

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

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  BannerAd? _bannerAd;

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

  @override
  void dispose() {
    _bannerAd?.dispose();
    super.dispose();
  }

  void _loadBannerAd() {
    _bannerAd = BannerAd(
      adUnitId: '你的AdMob横幅广告单元ID', // 替换为你的AdMob横幅广告单元ID
      size: AdSize.banner, // 或者其他你需要的尺寸
      listener: BannerAdListener(
        onAdLoaded: (_) {
          print('Banner Ad Loaded');
        },
        onAdFailedToLoad: (ad, error) {
          print('Banner Ad Failed to Load: ${error.message}');
          _bannerAd?.dispose();
          _bannerAd = null;
        },
      ),
    )..load();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('广告展示示例'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            _bannerAd?.widget ?? Container(), // 当广告加载完成后显示广告,否则显示一个空的Container
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                // 这里可以添加展示全屏广告或其他广告类型的代码
                // 例如:InterstitialAd().load().show();
              },
              child: Text('展示全屏广告'),
            ),
          ],
        ),
      ),
    );
  }
}

注意事项

  1. 广告单元ID:确保你使用了正确的广告单元ID。
  2. 测试广告:在开发模式下启用测试广告,以避免真实广告展示带来的费用。
  3. 权限和配置:根据广告平台的要求,确保你的应用配置了必要的权限和设置。

以上代码提供了一个基本的示例,展示了如何在Flutter应用中使用fastyle_ad插件来加载和展示横幅广告。根据你的需求,你可以进一步扩展和定制广告展示逻辑。

回到顶部