You*_*thm 1 android ads admob dart flutter
I'm working on an audiobook listening app. There I have my main page, which consists of 3 page widgets linked through a Page View that I can swipe to navigate through these pages. On each page I have laid exactly one banner ad from google_mobile_ads package. The problem is that if I add those 3 banners, my app starts to lag a lot, I did check the release version of my app, it is still laggy. In order to understand better the situation I will explain how my ad loading works.
I have a file, where I store the classes regarding those banner ads:
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:flutter/material.dart';
late AnchoredAdaptiveBannerAdSize adaptiveBannerSize;
class AdWidgets {
static Container? libraryPag;
static Container? homePag;
static Container? settingsPag;
}
void _setLoaded() {
AdState.loaded = true;
}
class AdState {
static bool loaded = false;
late Future<InitializationStatus> initialization;
AdState(this.initialization);
String get bannerAdUnitId => 'ca-app-pub-3940256099942544/6300978111';
BannerAdListener get adListener => _adListener;
BannerAdListener _adListener = BannerAdListener(
onAdLoaded: (ad) {
_setLoaded();
}
);
}
Run Code Online (Sandbox Code Playgroud)
There is the AdState class which I use to load my banner ads by providing them a BannerAdListener and an AdUnitId, the bool loaded is used in the widgets that display those banners in order for them to know if the ads where loaded and can be displayed properly.
Next I have a Stateful Widget Content, that I use to navigate through my app routes:
class _ContentState extends State<Content> with SingleTickerProviderStateMixin {
@override
void didChangeDependencies() {
// TODO: implement didChangeDependencies
super.didChangeDependencies();
final adState = Provider.of<AdState>(context);
adState.initialization.then((status) {
AdWidgets.libraryPag = Container(
width: MediaQuery.of(context).size.width,
height: adaptiveBannerSize.height.toDouble(),
child: AdWidget(
ad: BannerAd(
adUnitId: adState.bannerAdUnitId,
size: adaptiveBannerSize,
request: AdRequest(),
listener: adState.adListener
)
..load(),
)
);
AdWidgets.homePag = Container(
width: 320,
height: 100,
child: AdWidget(ad: BannerAd(
adUnitId: adState.bannerAdUnitId,
size: AdSize.largeBanner,
request: AdRequest(),
listener: adState.adListener
)
..load()),
);
AdWidgets.settingsPag = Container(
width: 320,
height: 250,
child: AdWidget(ad: BannerAd(
adUnitId: adState.bannerAdUnitId,
size: AdSize.mediumRectangle,
request: AdRequest(),
listener: adState.adListener
)
..load()
)
);
});
}
@override
Widget build(BuildContext context) {
return ValueListenableBuilder(
valueListenable: Settings.theme,
builder: (context, value, _) {
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
statusBarIconBrightness: Settings.theme.value == 'Dark' ? Brightness.light : Brightness.dark,
));
return WillPopScope(
onWillPop: () async {
if (bottomBarIndex.value != 1) {
moveHome();
}
return false;
},
child: Scaffold(
resizeToAvoidBottomInset: false,
body: Navigator(
key: Content.contentNavigatorKey,
initialRoute: '/',
onGenerateRoute: (RouteSettings settings) {
Widget builder;
switch (settings.name) {
case '/':
builder = MainPage();
break;
case '/bookPage':
Book book = settings.arguments as Book;
builder = BookPage(book: book);
bottomBarIndex.value = -1;
break;
case '/addBook':
builder = AddBookPage();
bottomBarIndex.value = -1;
break;
case '/changeCover':
Book book = settings.arguments as Book;
builder = ChangeCoverPage(book: book);
bottomBarIndex.value = -1;
break;
default:
throw Exception('Invalid route: ${settings.name}');
}
return PageRouteBuilder(
transitionDuration: Duration(milliseconds: 300),
transitionsBuilder:
(context, animation, secAnimation, child) {
animation = CurvedAnimation(
parent: animation, curve: Curves.easeIn);
return FadeTransition(
opacity: animation,
child: child,
);
},
pageBuilder: (context, animation, secAnimation) {
return builder;
});
},
onPopPage: (route, result) {
return route.didPop(result);
},
),
));
},
);
}
}
Run Code Online (Sandbox Code Playgroud)
In the didChangeDependencies method I initialize the adState (the way it is done in the Monetizing apps with Flutter official tutorial) and then assign three banner widgets to the each of the static Container from the AdWidgets custom class. Then I just display those Containers as I please, for example:
class LibraryPage extends StatefulWidget{
const LibraryPage({Key? key}) : super(key: key);
@override
_LibraryPageState createState() => _LibraryPageState();
}
class _LibraryPageState extends State<LibraryPage> with TickerProviderStateMixin {
late TabController _tabController;
late AppBar appBar;
@override
void initState() {
super.initState();
_tabController = TabController(length: 3, vsync: this);
appBar = AppBar(
brightness: Settings.theme.value == 'Dark' ? Brightness.dark : Brightness.light,
shadowColor: Settings.theme.value == 'Dark' ? Color.fromRGBO(0, 0, 0, 0.1) : Color.fromRGBO(0, 0, 0, 0.5),
backgroundColor: Settings.colors[2],
title: Text('Library'),
bottom: TabBar(
controller: _tabController,
labelPadding: EdgeInsets.zero,
labelStyle: TextStyle(
fontFamily: 'Montserrat',
fontWeight: FontWeight.w500
),
labelColor: Settings.colors[3],
indicator: UnderlineTabIndicator(
borderSide: BorderSide(color: Settings.colors[3], width: 2)
),
tabs: [
Tab(
text: 'Reading',
),
Tab(
text: 'New',
),
Tab(
text: 'Read',
)
],
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Settings.colors[1],
resizeToAvoidBottomInset: false,
appBar: appBar,
body: Column(
children: [
if (AdWidgets.libraryPag != null && AdState.loaded)
AdWidgets.libraryPag!
else
Container(
width: MediaQuery.of(context).size.width,
height: adaptiveBannerSize.height.toDouble(),
color: Settings.colors[0],
child: Center(
child: Text(
'Ad not loaded',
style: TextStyle(
color: Settings.colors[4],
fontFamily: 'Open Sans'),
)),
),
ScrollConfiguration(
behavior: MyBehavior(),
child: SizedBox(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height - appBar.preferredSize.height - appBar.bottom!.preferredSize.height - adaptiveBannerSize.height,
child: TabBarView(
controller: _tabController,
children: [
Category(category: 'reading'),
Category(category: 'new'),
Category(category: 'read')
],
),
),
),
],
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
As you can see there, I check if the AdWidgets.libraryPag is not null and if the ad was loaded and then if true - I display my ad.
The major issue is that - when I navigate from one page to another or scroll down it is very laggy even in the release build, also my bottomNavBar starts flickering a lot. Also when I do any kind of action in my app I get a stack of messages in of the console log saying D/AudioManager(30711): getStreamVolume isRestricted mode = 0. My guess is that the ads are reloading too often causing some performance issues.
Here is a small portion of my console log:
W/ContentCatcher(30711): Failed to notify a WebView
W/Choreographer(30711): Already have a pending vsync event. There should only be one at a time.
W/Choreographer(30711): OPTS_INPUT: First frame was drawed before optimized, so skip!
W/ContentCatcher(30711): Failed to notify a WebView
W/ContentCatcher(30711): Failed to notify a WebView
W/Choreographer(30711): Already have a pending vsync event. There should only be one at a time.
W/Choreographer(30711): Already have a pending vsync event. There should only be one at a time.
W/ContentCatcher(30711): Failed to notify a WebView
W/ContentCatcher(30711): Failed to notify a WebView
W/Choreographer(30711): OPTS_INPUT: First frame was drawed before optimized, so skip!
W/Choreographer(30711): OPTS_INPUT: First frame was drawed before optimized, so skip!
W/ContentCatcher(30711): Failed to notify a WebView
I/Ads (30711): Use RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("B0B49AF69923DB48675A21F6F88D2525")) to get test ads on this device.
D/AudioManager(30711): getStreamVolume isRestricted mode = 0
D/AudioManager(30711): getStreamVolume isRestricted mode = 0
Run Code Online (Sandbox Code Playgroud)
How can I fix this performance issue?
参考这个问题的答案, Android 10之前的AndroidView应该有更好的性能。如果是这种情况,也许我们可以检查设备操作系统并使用 AndroidView 而不是 PlatformViewLink。
atrope从 repo google_mobile_ads中创建 fork并执行此技巧,以便为低于 Android 10 的设备操作系统提供更好的性能
在您的 pubspec.yaml 中使用此存储库而不是官方 google_ads
google_mobile_ads:
git:
url: https://github.com/SuaMusica/googleads-mobile-flutter.git
path: packages/google_mobile_ads
ref: feature/suamusica
Run Code Online (Sandbox Code Playgroud)
特别感谢阿托普
| 归档时间: |
|
| 查看次数: |
1876 次 |
| 最近记录: |