How to implement Native ads in your flutter application.
How to implement Native ads in your flutter application.
Native ads are a type of ad assets that are placed among other content of your app and you can change ad values such as font and color. Native advertising can significantly increase your monetization. Here we will integrate the Native ad in our application.
main.dart
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | import 'package:flutter/material.dart'; import 'package:native_admob_flutter/native_admob_flutter.dart'; import 'package:nativeadapp/ads/native_ads.dart'; Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); await MobileAds.initialize(); MobileAds.setTestDeviceIds(['9345804C1E5765DHG1DFE29CA0758842']); runApp(MyApp()); } class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp(debugShowCheckedModeBanner: false, title: 'Flutter Native Ad', theme: ThemeData(brightness:Brightness.dark, // This is the theme of your application. // // Try running your application with "flutter run". You'll see the // application has a blue toolbar. Then, without quitting the app, try // changing the primarySwatch below to Colors.green and then invoke // "hot reload" (press "r" in the console where you ran "flutter run", // or simply save your changes to "hot reload" in a Flutter IDE). // Notice that the counter didn't reset back to zero; the application // is not restarted. primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Native Ad'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key? key, required this.title}) : super(key: key); // This widget is the home page of your application. It is stateful, meaning // that it has a State object (defined below) that contains fields that affect // how it looks. // This class is the configuration for the state. It holds the values (in this // case the title) provided by the parent (in this case the App widget) and // used by the build method of the State. Fields in a Widget subclass are // always marked "final". final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { // This call to setState tells the Flutter framework that something has // changed in this State, which causes it to rerun the build method below // so that the display can reflect the updated values. If we changed // _counter without calling setState(), then the build method would not be // called again, and so nothing would appear to happen. _counter++; }); } @override Widget build(BuildContext context) { // This method is rerun every time setState is called, for instance as done // by the _incrementCounter method above. // // The Flutter framework has been optimized to make rerunning build methods // fast, so that you can just rebuild anything that needs updating rather // than having to individually change instances of widgets. return Scaffold( appBar: AppBar( // Here we take the value from the MyHomePage object that was created by // the App.build method, and use it to set our appbar title. title: Text(widget.title), ), body: ListView(children: [ Container(height: 330,child: NativeAds()), Image.asset('assets/Psiphon.jpg',fit: BoxFit.fitWidth,), Image.asset('assets/graph.png',fit: BoxFit.fitWidth,), ],), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add), ), // This trailing comma makes auto-formatting nicer for build methods. ); } } |
native_ads.dart
lib/ads/native_ads.dart
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 | import 'package:flutter/material.dart'; import 'package:native_admob_flutter/native_admob_flutter.dart'; class NativeAds extends StatefulWidget { const NativeAds({Key? key}) : super(key: key); @override _NativeAdsState createState() => _NativeAdsState(); } class _NativeAdsState extends State<NativeAds> with AutomaticKeepAliveClientMixin { final controller = NativeAdController(); @override void initState() { // TODO: implement initState super.initState(); controller.load(keywords: ['car', 'sport']); controller.onEvent.listen((event) { setState(() {}); }); } @override void dispose() { controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return controller.isLoaded ? NativeAd( height: 330, unitId: 'ca-app-pub-91171565522331864637/94742581946754', // unitId: MobileAds.nativeAdTestUnitId, loading: Text('loading'), error: Text('Ads failed to load'), icon: AdImageView(size: 80), headline: AdTextView( padding: EdgeInsets.only(bottom: 10), style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, color: Colors.white), maxLines: 1, ), media: AdMediaView( height: 180, width: MATCH_PARENT, ), attribution: AdTextView( width: WRAP_CONTENT, text: 'Ad', decoration: AdDecoration( border: BorderSide(color: Colors.green, width: 2), borderRadius: AdBorderRadius.all(16)), style: TextStyle(color: Colors.green), padding: EdgeInsets.symmetric(horizontal: 4.0, vertical: 1.0), ), button: AdButtonView( decoration: AdDecoration(backgroundColor: Colors.blue), elevation: 18, textStyle: TextStyle(color: Colors.white), height: MATCH_PARENT, ), buildLayout: fullBuilder, ) : SizedBox( height: 330, ); } @override // TODO: implement wantKeepAlive bool get wantKeepAlive => true; } AdLayoutBuilder get fullBuilder => (ratingBar, media, icon, headline, advertiser, body, price, store, attribuition, button) { return AdLinearLayout( decoration: AdDecoration( backgroundColor: Colors.black54, ), padding: EdgeInsets.all(10), // The first linear layout width needs to be extended to the // parents height, otherwise the children won't fit good width: MATCH_PARENT, children: [ media, AdLinearLayout( children: [ icon, AdLinearLayout(children: [ headline, AdLinearLayout( children: [attribuition, advertiser, ratingBar], orientation: HORIZONTAL, width: MATCH_PARENT, ), ], margin: EdgeInsets.only(left: 4)), ], gravity: LayoutGravity.center_horizontal, width: WRAP_CONTENT, orientation: HORIZONTAL, margin: EdgeInsets.only(top: 6), ), AdLinearLayout( children: [button], orientation: HORIZONTAL, ), ], ); }; |
pubspec.yaml
Add this to your package’s pubspec.yaml file:
native_admob_flutter: ^1.4.0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | name: nativeadapp description: A new Flutter project. # The following line prevents the package from being accidentally published to # pub.dev using `pub publish`. This is preferred for private packages. publish_to: 'none' # Remove this line if you wish to publish to pub.dev # The following defines the version and build number for your application. # A version number is three numbers separated by dots, like 1.2.43 # followed by an optional build number separated by a +. # Both the version and the builder number may be overridden in flutter # build by specifying --build-name and --build-number, respectively. # In Android, build-name is used as versionName while build-number used as versionCode. # Read more about Android versioning at https://developer.android.com/studio/publish/versioning # In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion. # Read more about iOS versioning at version: 1.0.0+1 environment: sdk: ">=2.12.0 <3.0.0" dependencies: flutter: sdk: flutter # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^1.0.2 native_admob_flutter: ^1.4.0 dev_dependencies: flutter_test: sdk: flutter # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec # The following section is specific to Flutter. flutter: # The following line ensures that the Material Icons font is # included with your application, so that you can use the icons in # the material Icons class. uses-material-design: true # To add assets to your application, add an assets section, like this: assets: - assets/ # An image asset can refer to one or more resolution-specific "variants", see # For details regarding adding assets from package dependencies, see # To add custom fonts to your application, add a fonts section here, # in this "flutter" section. Each entry in this list should have a # "family" key with the font family name, and a "fonts" key with a # list giving the asset and other descriptors for the font. For # example: # fonts: # - family: Schyler # fonts: # - asset: fonts/Schyler-Regular.ttf # - asset: fonts/Schyler-Italic.ttf # style: italic # - family: Trajan Pro # fonts: # - asset: fonts/TrajanPro.ttf # - asset: fonts/TrajanPro_Bold.ttf # weight: 700 # # For details regarding fonts from package dependencies, |
android/app/src/main/AndroidManifest.xml
Add your Admob App ID to AndroidManifest.xml :
<uses-permission android:name=”android.permission.INTERNET” />
<meta-data android:name=”com.google.android.gms.ads.APPLICATION_ID” android:value=”ca-app-pub-911715624454554637~99608545484″/>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.splashscreenapp"> <uses-permission android:name="android.permission.INTERNET" /> <application android:label="splashscreenapp" android:icon="@mipmap/ic_launcher"> <activity android:name=".MainActivity" android:launchMode="singleTop" android:theme="@style/LaunchTheme" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode" android:hardwareAccelerated="true" android:windowSoftInputMode="adjustResize"> <!-- Specifies an Android theme to apply to this Activity as soon as the Android process has started. This theme is visible to the user while the Flutter UI initializes. After that, this theme continues to determine the Window background behind the Flutter UI. --> <meta-data android:name="io.flutter.embedding.android.NormalTheme" android:resource="@style/NormalTheme" /> <!-- Displays an Android View that continues showing the launch screen Drawable until Flutter paints its first frame, then this splash screen fades out. A splash screen is useful to avoid any visual gap between the end of Android's launch screen and the painting of Flutter's first frame. --> <meta-data android:name="io.flutter.embedding.android.SplashScreenDrawable" android:resource="@drawable/launch_background" /> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> <!-- Don't delete the meta-data below. This is used by the Flutter tool to generate GeneratedPluginRegistrant.java --> <meta-data android:name="flutterEmbedding" android:value="2" /> <meta-data android:name="com.google.android.gms.ads.APPLICATION_ID" android:value="ca-app-pub-911715624354564637~9545645184"/> </application> </manifest> |