0

i am learning flutter and following the tutorial (https://codelabs.developers.google.com/codelabs/admob-ads-in-flutter#7) to create admob. It is currently below the bottomNavigationBar. However, if another phone has smaller screen size, bottomNavigationBar will overlap with the banner. How can i adjust the padding according to dp?

i have tired admob_flutter (https://pub.dev/packages/admob_flutter) a bit, but don't know where to put this code (https://stackoverflow.com/a/61954531/7972213)

enter image description here

// home.dart
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:geolocator/geolocator.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_admob/firebase_admob.dart';
import 'package:flutter_geolocation/ad_manager.dart';

// import 'package:firebase_analytics/firebase_analytics.dart';
// import 'package:firebase_auth/firebase_auth.dart';

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  bool mapToggle = false;
  GoogleMapController mapController;
  Position _currentPosition;
  List<Marker> allMarkers = [];

  Future<void> _initAdMob() {
    // TODO: Initialize AdMob SDK
    return FirebaseAdMob.instance.initialize(appId: AdManager.appId);
  }

  // TODO: Add _bannerAd
  BannerAd _bannerAd;

  // TODO: Implement _loadBannerAd()
  void _loadBannerAd() {
    _bannerAd
      ..load()
      ..show(anchorType: AnchorType.bottom);
  }

  _getCurrentLocation() async {
    Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
        .then((Position position) {
      setState(() {
        _currentPosition = position;
        mapToggle = true;
        _populateClients();
      });
    }).catchError((e) {
      print(e);
    });
  }

  _populateClients() {
    CollectionReference ref = FirebaseFirestore.instance.collection('markers');
    ref.get().then((doc) {
      if (doc.docs.isNotEmpty) {
        setState(() {
          for (int i = 0; i < doc.docs.length; i++) {
            final marker = Marker(
              markerId: MarkerId(doc.docs[i].data()['clientName']),
              position: LatLng(doc.docs[i].data()['location'].latitude,
                  doc.docs[i].data()['location'].longitude),
              infoWindow: InfoWindow(
                title: doc.docs[i].data()['clientName'],
                snippet: 'test',
              ),
              draggable: false,
            );
            allMarkers.add(marker);
          }
        });
      }
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getCurrentLocation();
    // TODO: Initialize _bannerAd
    _bannerAd = BannerAd(
      adUnitId: AdManager.bannerAdUnitId,
      size: AdSize.banner,
    );

    // TODO: Load a Banner Ad
    _loadBannerAd();
  }

  void _onMapCreated(controller) {
    setState(() {
      mapController = controller;
    });
  }

  int _selectedIndex = 0;

  @override
  void dispose() {
    // TODO: Dispose BannerAd object
    _bannerAd?.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Home'),
      ),
      body: mapToggle
          ? GoogleMap(
              onMapCreated: _onMapCreated,
              initialCameraPosition: CameraPosition(
                  target: LatLng(
                      _currentPosition.latitude, _currentPosition.longitude),
                  zoom: 10.0),
              markers: Set.from(allMarkers),
            )
          : Center(
              child: Text(
              'Map Loading.. Please wait..',
              style: TextStyle(fontSize: 20.0),
            )),
      bottomNavigationBar: Padding(
        padding: const EdgeInsets.only(bottom: 50),
        child: BottomNavigationBar(
          items: const <BottomNavigationBarItem>[
            BottomNavigationBarItem(
              icon: Icon(Icons.map),
              label: 'Map',
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.subtitles),
              label: 'TBD',
            ),
          ],
          backgroundColor: Colors.green[100],
          type: BottomNavigationBarType.fixed,
          currentIndex: _selectedIndex,
          selectedItemColor: Colors.amber[800],
          // onTap: _onItemTapped,
        ),
      ),
    );
  }
}
Matthias
  • 348
  • 3
  • 11

1 Answers1

2

Here is the trick to place the add at the bottom and reduce the size of the map. use

return Scaffold(
    appBar: AppBar(
      title: Text('Home'),
    ),
    bottomNavigationBar: Container(
      height: adSize,
      color: Colors.transparent,
    ),
    body: ... widget ...);
}

To show the ad at the bottom remove AnchorType.top and after successful call of show banner ad, call

setState(() {
        adSize =  _bannerAd.size.height.toDouble();
      });
Faiizii Awan
  • 1,615
  • 1
  • 13
  • 28
  • how about i already have a bottomNavigationBar and wanted to have banner below the bottomNavigationBar? I tried to add padding for 50 but it can't adjust for different screen size. I revised my code and screenshot above. – Matthias Nov 26 '20 at 03:01
  • wrap your bottom nav widget and ad container inside a column widget – Faiizii Awan Nov 26 '20 at 03:55