Flutter, error with new google mobile ads sdk - flutter

I'm having issues just using google_mobile_ads, when I try the method in the flutter tutorial I don't know how to make it work in my main
main
import 'package:android_alarm_manager/android_alarm_manager.dart';
import 'package:behend/admob_service.dart';
import 'package:behend/provider/alarm_manager.dart';
import 'package:behend/provider/alarm_provider.dart';
import 'package:behend/provider/setting_provider.dart';
import 'package:behend/provider/stats_provider.dart';
import 'package:behend/screen/Tooltips/intro.dart';
import 'package:behend/screen/alarm_appear_screen.dart';
import 'package:behend/utils/app_preference_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_statusbarcolor/flutter_statusbarcolor.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'generated/l10n.dart';
import 'admob_service.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
///para los ads =v
final initFuture = MobileAds.instance.initialize();
final adState = AdState(initFuture);
SystemChrome.setSystemUIOverlayStyle(
SystemUiOverlayStyle(statusBarIconBrightness: Brightness.dark));
await AndroidAlarmManager.initialize();
SharedPreferences.getInstance().then((value) {
AppPreferenceUtil(pref: value);
runApp(MultiProvider(
providers: [
Provider.value(
value: adState,
builder: (context, child)),
ChangeNotifierProvider(
create: (_) => AlarmManager(),
),
ChangeNotifierProvider(
create: (_) => SettingProvider(),
),
ChangeNotifierProvider(
create: (_) => AlarmProvider.full(),
),
ChangeNotifierProvider(
create: (_) => StatsProvider(),
)
],
child: MyApp(),
));
});
//runApp(MyApp());
}
Future<void> alarm() async {
print("launching alarm entry point____----___");
WidgetsFlutterBinding.ensureInitialized();
await AndroidAlarmManager.initialize();
SharedPreferences.getInstance().then((value) {
AppPreferenceUtil(pref: value);
runApp(MultiProvider(providers: [
ChangeNotifierProvider(
create: (_) => AlarmManager(),
),
ChangeNotifierProvider(
create: (_) => AlarmProvider.minimal(),
)
], child: MyApp2()));
});
//runApp(MyApp());
}
class MyApp2 extends StatefulWidget {
#override
_MyApp2State createState() => _MyApp2State();
}
class _MyApp2State extends State<MyApp2> {
#override
void initState() {
FlutterStatusbarcolor.setStatusBarWhiteForeground(true);
Provider.of<AlarmManager>(context, listen: false).init(context);
super.initState();
}
#override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
]);
return AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
),
child: MaterialApp(
title: 'Behend',
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
S.delegate,
],
supportedLocales:
///[
/// const Locale('en', ''),
///const Locale('es', ''),
///],
S.delegate.supportedLocales,
theme: ThemeData(
// 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.teal,
// This makes the visual density adapt to the platform that you run
// the app on. For desktop platforms, the controls will be smaller and
// closer together (more dense) than on mobile platforms.
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: Consumer<AlarmManager>(
builder: (context, provider, child) {
return AlarmAppearScreen(provider.currentAlarmId);
},
),
),
);
}
}
class MyApp extends StatelessWidget {
/*static final FirebaseAnalytics analytics = FirebaseAnalytics();
static final FirebaseAnalyticsObserver observer =
FirebaseAnalyticsObserver(analytics: analytics);
// This widget is the root of your application.*/
#override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
]);
// uncomment this and open this function
//updateScoreCard();
return AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
),
child: MaterialApp(
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
S.delegate,
],
supportedLocales:
///[
///const Locale('en', ''),
///const Locale('es', ''),
///],
S.delegate.supportedLocales,
title: 'Behend',
theme: ThemeData(
// 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,
// This makes the visual density adapt to the platform that you run
// the app on. For desktop platforms, the controls will be smaller and
// closer together (more dense) than on mobile platforms.
visualDensity: VisualDensity.adaptivePlatformDensity,
),
//home: EasySortScreen(),
// home: SwitchExample(),
// home: HomeScreen(), --
home: Intro(),
navigatorObservers: <NavigatorObserver>[/*observer*/],
),
);
}
adstate
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'dart:io';
class AdState {
Future<InitializationStatus> initialization;
AdState(this.initialization);
static String get bannerAdUnitId => Platform.isAndroid
///El primer id es para android
? 'ca-app-pub-3940256099942544/6300978111'
///El segundo id es para IOS
: 'ca-app-pub-3940256099942544/6300978111';
}
yaml
name: behend
description: A new Flutter application.
# 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
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.5.39+29
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
google_mobile_ads: ^0.11.0+3
dart_random_choice: ^0.0.2
curved_navigation_bar:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
cupertino_icons: ^0.1.3
provider: ^4.1.2
percent_indicator: "^2.1.1"
package_info: ^0.4.0+16
fl_chart: 0.9.4
shared_preferences: ^0.5.7+3
intl: ^0.17.0
vibration: ^1.4.0
showcaseview: ^0.1.5
fluttertoast: ^3.1.0
android_alarm_manager:
path: ./android_alarm_manager-0.4.5_11
#parece que no funciona(deprecated) o pisa el nuevo package de google_mobile_ads
#(tira error con el package de google ads(si se quita no lo lo tira))
#firebase_analytics:
# path: ./firebase_analytics-5_0_16
flutter_swiper: 1.1.6
flutter_tindercard: 0.1.8
url_launcher: 5.4.10
flutter_reorderable_list: ^0.1.4
flutter_statusbarcolor: 0.2.3
after_layout: ^1.0.7+2
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/
- assets/images/
- assets/images/intro-slider/
- assets/images/Tooltips/
- assets/icons/
- assets/icons/2.0x/
- assets/icons/3.0x/
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# 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: Circular
fonts:
- asset: assets/fonts/CircularStd-Black.ttf
- asset: assets/fonts/CircularStd-Bold.ttf
- family: Roboto
fonts:
- asset: assets/fonts/Roboto-Bold.ttf
- asset: assets/fonts/Roboto-Regular.ttf
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
flutter_intl:
enabled: true
main_locale: en
class_name: S
Since I cannot pass context in that list in my main I tried some other method that in found in Youtube
main
import 'package:android_alarm_manager/android_alarm_manager.dart';
import 'package:behend/admob_service.dart';
import 'package:behend/provider/alarm_manager.dart';
import 'package:behend/provider/alarm_provider.dart';
import 'package:behend/provider/setting_provider.dart';
import 'package:behend/provider/stats_provider.dart';
import 'package:behend/screen/Tooltips/intro.dart';
import 'package:behend/screen/alarm_appear_screen.dart';
import 'package:behend/utils/app_preference_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_statusbarcolor/flutter_statusbarcolor.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'generated/l10n.dart';
import 'admob_service.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
AdMobService.initialize();
/*
///para los ads =v
final initFuture = MobileAds.instance.initialize();
final adState = AdState(initFuture);
*/
SystemChrome.setSystemUIOverlayStyle(
SystemUiOverlayStyle(statusBarIconBrightness: Brightness.dark));
await AndroidAlarmManager.initialize();
SharedPreferences.getInstance().then((value) {
AppPreferenceUtil(pref: value);
runApp(MultiProvider(
providers: [
/*Provider.value(
value: adState,
builder: (context, child)),*/
ChangeNotifierProvider(
create: (_) => AlarmManager(),
),
ChangeNotifierProvider(
create: (_) => SettingProvider(),
),
ChangeNotifierProvider(
create: (_) => AlarmProvider.full(),
),
ChangeNotifierProvider(
create: (_) => StatsProvider(),
)
],
child: MyApp(),
));
});
//runApp(MyApp());
}
Future<void> alarm() async {
print("launching alarm entry point____----___");
WidgetsFlutterBinding.ensureInitialized();
await AndroidAlarmManager.initialize();
SharedPreferences.getInstance().then((value) {
AppPreferenceUtil(pref: value);
runApp(MultiProvider(providers: [
ChangeNotifierProvider(
create: (_) => AlarmManager(),
),
ChangeNotifierProvider(
create: (_) => AlarmProvider.minimal(),
)
], child: MyApp2()));
});
//runApp(MyApp());
}
class MyApp2 extends StatefulWidget {
#override
_MyApp2State createState() => _MyApp2State();
}
class _MyApp2State extends State<MyApp2> {
#override
void initState() {
FlutterStatusbarcolor.setStatusBarWhiteForeground(true);
Provider.of<AlarmManager>(context, listen: false).init(context);
super.initState();
}
#override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
]);
return AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
),
child: MaterialApp(
title: 'Behend',
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
S.delegate,
],
supportedLocales:
///[
/// const Locale('en', ''),
///const Locale('es', ''),
///],
S.delegate.supportedLocales,
theme: ThemeData(
// 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.teal,
// This makes the visual density adapt to the platform that you run
// the app on. For desktop platforms, the controls will be smaller and
// closer together (more dense) than on mobile platforms.
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: Consumer<AlarmManager>(
builder: (context, provider, child) {
return AlarmAppearScreen(provider.currentAlarmId);
},
),
),
);
}
}
class MyApp extends StatelessWidget {
/*static final FirebaseAnalytics analytics = FirebaseAnalytics();
static final FirebaseAnalyticsObserver observer =
FirebaseAnalyticsObserver(analytics: analytics);
// This widget is the root of your application.*/
#override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
]);
// uncomment this and open this function
//updateScoreCard();
return AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
),
child: MaterialApp(
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
S.delegate,
],
supportedLocales:
///[
///const Locale('en', ''),
///const Locale('es', ''),
///],
S.delegate.supportedLocales,
title: 'Behend',
theme: ThemeData(
// 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,
// This makes the visual density adapt to the platform that you run
// the app on. For desktop platforms, the controls will be smaller and
// closer together (more dense) than on mobile platforms.
visualDensity: VisualDensity.adaptivePlatformDensity,
),
//home: EasySortScreen(),
// home: SwitchExample(),
// home: HomeScreen(), --
home: Intro(),
navigatorObservers: <NavigatorObserver>[/*observer*/],
),
);
}
adState
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'dart:io';
/*
class AdState {
Future<InitializationStatus> initialization;
AdState(this.initialization);
static String get bannerAdUnitId => Platform.isAndroid
///El primer id es para android
? 'ca-app-pub-3940256099942544/6300978111'
///El segundo id es para IOS
: 'ca-app-pub-3940256099942544/6300978111';
}
*/
class AdMobService {
static String get bannerAdUnitId => Platform.isAndroid
///El primer id es para android
? 'ca-app-pub-3940256099942544/6300978111'
///El segundo id es para IOS
: 'ca-app-pub-3940256099942544/6300978111';
static initialize () {
if (MobileAds.instance == null){
MobileAds.instance.initialize();
}
}
static BannerAd createBannerAd() {
BannerAd ad = new BannerAd(
adUnitId: bannerAdUnitId,
size: AdSize.banner,
request: AdRequest(),
listener: AdListener(
onAdLoaded: (Ad ad) => print("Ad loaded"),
onAdFailedToLoad: (Ad ad, LoadAdError error) {
ad.dispose();
},
onAdOpened: (Ad ad) => print("ad opened"),
onAdClosed: (Ad ad) => print("ad closed")
)
);
return ad;
}
}
Here it run but it gives me this error (only happens when I have google_mobile_ads package activated)
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:processDebugResources'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
> Android resource linking failed
C:\Users\negre\.gradle\caches\transforms-2\files-2.1\6860be4bd435a3ae0d9b52a862c3efa5\play-services-ads-lite-19.7.0\AndroidManifest.xml:27:5-43:15: AAPT: error: unexpected element <queries> found in <manifest>.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 18s
The build failed likely due to AndroidX incompatibilities in a plugin. The tool is about to try using Jetifier to solve the incompatibility.
Building plugin android_alarm_manager...
Running Gradle task 'assembleAarRelease'...
√ Built build\app\outputs\repo.
Building plugin flutter_statusbarcolor...
Running Gradle task 'assembleAarRelease'...
√ Built build\app\outputs\repo.
Building plugin fluttertoast...
Running Gradle task 'assembleAarRelease'...
√ Built build\app\outputs\repo.
Building plugin google_mobile_ads...
Running Gradle task 'assembleAarRelease'...
FAILURE: Build failed with an exception.
* Where:
Build file 'C:\Users\negre\AppData\Local\Pub\Cache\hosted\pub.dartlang.org\google_mobile_ads-0.11.0+3\android\build.gradle' line: 22
* What went wrong:
A problem occurred evaluating root project 'google_mobile_ads'.
> Failed to apply plugin [id 'com.android.internal.version-check']
> Minimum supported Gradle version is 6.5. Current version is 5.6.4. If using the gradle wrapper, try editing the distributionUrl in C:\Users\negre\AppData\Local\Pub\Cache\hosted\pub.dartlang.org\google_mobile_ads-0.11.0+3\android\gradle\wrapper\gradle-wrapper.properties to gradle-6.5-all.zip
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 1s
Exception: The plugin google_mobile_ads could not be built due to the issue above.

android/build.gradle
open build.gradle file.
Check if the Android Gradle Plugin 4.1 or higher. If it's less than 4.1 then change the Gradle Plugin as like the following code
dependencies {
classpath 'com.android.tools.build:gradle:4.1.0'
...
}
android/gradle/wrapper/gradle-wrapper.properties
open gradle-wrapper.properties file. Change the distributionUrl to the following line.
distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip
then run the flutter clean command
at last, restart the IDE and build the app.
This is how I solve this problem. Hope this will solve your problem too.

Related

Error: change the path of the translation files using EasyLocalization Flutter

I´m new using flutter and I'm trying to implement EasyLocalization in my project, I have two project, one for the json files and other to the app, but I don't know how I can set the path to recognize the files hosted in the project of the traslations. Below my code:
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:jarvis_ui/jarvis_ui.dart';
import './src/ui/view/view.dart';
import 'idle.dart';
import 'src/ui/ui.dart';
import 'src/ui/view/error/error.dart';
Future<void> main() async {
String defaultRoute = window.defaultRouteName;
Uri _uri = Uri.parse(defaultRoute);
WidgetsFlutterBinding.ensureInitialized();
await EasyLocalization.ensureInitialized();
await SystemChrome.setPreferredOrientations(
<DeviceOrientation>[
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
],
);
runApp(
EasyLocalization(
supportedLocales: <Locale>[
Locale('es', 'CL'),
Locale('es', 'CO'),
Locale('es', 'PE'),
],
fallbackLocale: Locale('es', 'CL'),
path: 'packages/ui_shared/assets/languages',
assetLoader: RootBundleAssetLoader(),
child: ProviderScope(
observers: <ProviderObserver>[
// Logger(),
],
child: MyApp(params: _uri.queryParameters),
),
),
);
}
class MyApp extends HookWidget {
const MyApp({required this.params});
final Map<String, dynamic> params;
#override
Widget build(BuildContext context) => IdleApp(params: params);
}
In import 'package:jarvis_ui/jarvis_ui.dart'; is hosted the json files for the traslations. Then, I think that the correct way to assign the path was: path: 'packages/ui_shared/assets/languages', but I was wrong. The error is here:
In the pubspec.yaml of project that I have the json files stored, I have this:
flutter:
assets:
- assets/languages/
Thank you so much if you can help me with this.

Flutter - Nullability problem with Locale

Below code has no compiler warnings or errors. Running it results in:
lib/main.dart:26:51: Error: The argument type 'Locale?' can't be assigned to the parameter type 'Locale' because 'Locale?' is nullable and 'Locale' isn't.
- 'Locale' is from 'dart:ui'.
thisAppsLocaleNotifier = ValueNotifier(window.locale);
^
lib/main.dart:27:43: Error: Property 'languageCode' cannot be accessed on 'Locale?' because it is potentially null.
- 'Locale' is from 'dart:ui'.
Try accessing using ?. instead.
Localization.langCode = window.locale.languageCode;
^^^^^^^^^^^^
Failed to compile application.
Neither window nor locale could be null. No parameters here can be null. The error message is quite annoying because trying
thisAppsLocaleNotifier = ValueNotifier(window.locale ?? Locale('en'));
Results in a compiler warning:
The left operand can't be null, so the right operand is never executed. Try removing the operator and the right operand.
This is the code:
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'main.i18n.dart';
/// Supported locales. First entry `en` is default.
const List<Locale> supportedLocales = [
Locale('en', 'US'),
Locale('de', 'DE'),
Locale('es', 'ES'),
];
late ValueNotifier<Locale> thisAppsLocaleNotifier;
/// Entry point for example application
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
MyApp() {
thisAppsLocaleNotifier = ValueNotifier(window.locale);
Localization.langCode = window.locale.languageCode;
}
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return ValueListenableBuilder(
valueListenable: thisAppsLocaleNotifier,
builder: (BuildContext context, Locale thisAppsLocale, Widget? child) =>
MaterialApp(
home: MyHomePage(),
locale: thisAppsLocale,
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: supportedLocales,
theme: ThemeData(
primarySwatch: Colors.orange,
),
title: 'input_country',
),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
print('_MyHomePageState build');
return Scaffold(
appBar: AppBar(
title: Text('App Title'.i18n),
),
body: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text('thisAppsLocale = ${thisAppsLocaleNotifier.value} / langCode ='
' ${Localization.langCode}'),
ButtonBar(
alignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () => setLocale(Locale('de')),
child: Text('de'),
),
ElevatedButton(
onPressed: () => setLocale(Locale('en')),
child: Text('en'),
),
ElevatedButton(
onPressed: () => setLocale(Locale('es')),
child: Text('es'),
),
],
)
],
),
),
);
}
void setLocale(Locale newLocale) {
Localization.langCode = newLocale.languageCode;
thisAppsLocaleNotifier.value = newLocale;
}
}
And this is pubspec.yaml
name: qq
description: A new Flutter application.
publish_to: 'none'
version: 1.0.0+1
environment:
sdk: ">=2.12.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
What is required to run the code in null-safety mode?
This is the localization class main.i18n.dart:
extension Localization on String {
static String langCode = 'en';
String get i18n => localize(this, _t);
static final Map<String, Map<String, String>> _t = {
'All': {
'de': 'Alle',
'es': 'Todas',
},
'Example': {
'de': 'Beispiel',
'es': 'Ejemplo',
},
'Languages': {
'de': 'Sprachen',
'es': 'Idiomas',
},
'Selectables': {
'de': 'Einträge',
'es': 'Entradas',
},
};
String localize(String english, Map<String, Map<String, String>> t10ns) {
if (langCode != 'en') {
Map<String, String>? _t10ns = t10ns[english];
if (_t10ns == null) {
print('No translations found for "$english"');
} else {
String? translated = _t10ns[langCode];
if (translated == null) {
print('Translation to language "$langCode" missing for "$english"');
} else {
return translated;
}
}
}
return english;
}
}
Output of Flutter doctor:
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.0.3, on Microsoft Windows [Version 10.0.19042.867], locale de-DE)
[√] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
[√] Chrome - develop for the web
[√] Android Studio (version 4.1.0)
[√] Connected device (3 available)
• No issues found!
It looks like it was a bug with flutter web. It should be fixed in one of the next releases
https://github.com/flutter/engine/pull/24922
What you can do for now to make it work on web and avoid warnings on desktop or mobiles:
Create 3 files:
shared.dart
mobile.dart
web.dart
// shared.dart
export 'web.dart' if (dart.library.io) 'mobile.dart';
// mobile.dart
import 'dart:ui';
Locale getLocale() => window.locale;
// web.dart
import 'dart:ui';
// ignore: unnecessary_non_null_assertion
Locale getLocale() => window.locale!;
Then in your code, only import shared.dart and get the Locale from there:
main.dart
import 'shared.dart';
final Locale locale = getLocale();
There is a comprehensive explanation of null safety here: Null safety in Flutter. It includes a link to the migration guide that will help you migrate your code.
Note that in the pubspec:
environment:
sdk: ">=2.12.0 <3.0.0"
specifying the sdk version >=2.12.0 enables null safety, with the consequent checks. Specifying any earlier version will disable null safety.
In order to fix your code for null safety, you need to check for non-null values where they are not permitted - the error messages generally point this out. So the errors:
lib/main.dart:26:51: Error: The argument type 'Locale?' can't be assigned to the parameter type 'Locale' because 'Locale?' is nullable and 'Locale' isn't.
- 'Locale' is from 'dart:ui'.
thisAppsLocaleNotifier = ValueNotifier(window.locale);
lib/main.dart:27:43: Error: Property 'languageCode' cannot be accessed on 'Locale?' because it is potentially null.
- 'Locale' is from 'dart:ui'.
Try accessing using ?. instead.
Localization.langCode = window.locale.languageCode;
can be fixed by asserting that the parameter is not null using window.locale!.
Your frustration with window.locale ?? ... was caused because this does not check for window being null.

Flutter Play Sound and Record Noise Levels

Can anybody help plz!
Ive been running into this issue for a while now. The app runs fine on an ios simulator aswell as android device but not on an ios device. The general idea is that i want a tone to play and once that tone starts playing i need to record the decibel levels that the device picks up. From what i understand, the ios device only allows for one channel to be used at a time, wheather it be input or output. I am using the audioplayers and noise_meter plugins. All permissions have been granted and if i run the one method alone it works and visa versa but when running both methods it throws this error.
https://pub.dev/packages/noise_meter
https://pub.dev/packages/audioplayers
The errors i am receiving are below:
"iOS => call startHeadlessService, playerId fa642ed8-2266-48b6-ac9f-1f474f225864"
"calling start headless service (\n 4430477584143042153\n)"
"iOS => call setReleaseMode, playerId fa642ed8-2266-48b6-ac9f-1f474f225864"
"iOS => call play, playerId fa642ed8-2266-48b6-ac9f-1f474f225864"
"setUrl /var/mobile/Containers/Data/Application/0E0D63C7-B1DD-4BD3-BC84-2AFB5C80B8D9/Library/Caches/2100.mp3"
[VERBOSE-2:FlutterObservatoryPublisher.mm(101)] Failed to register observatory port with mDNS with error -65555.
[VERBOSE-2:FlutterObservatoryPublisher.mm(103)] On iOS 14+, local network broadcast in apps need to be declared in the app's Info.plist. Debug and profile Flutter apps and modules host VM services on the local network to support debugging features such as hot reload and DevTools. To make your Flutter app or module attachable and debuggable, add a '_dartobservatory._tcp' value to the 'NSBonjourServices' key in your Info.plist for the Debug/Profile configurations. For more information, see https://flutter.dev/docs/development/add-to-app/ios/project-setup#local-network-privacy-permissions
""
"iOS -> updateDuration...1.541224"
"iOS -> invokechannel"
"iOS -> onSoundComplete..."
[avas] AVAudioSession_iOS.mm:1149 Deactivating an audio session that has running I/O. All I/O should be stopped or paused prior to deactivating the audio session.
"Error inactivating audio session Error Domain=NSOSStatusErrorDomain Code=560030580 \"(null)\""
Ive put a simple application together to merely demonstrate my issue:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:audioplayers/audio_cache.dart';
import 'package:flutter/services.dart';
import 'package:noise_meter/noise_meter.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// 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 Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
static AudioCache player = AudioCache();
bool _isRecording = false;
StreamSubscription<NoiseReading> _noiseSubscription;
NoiseMeter _noiseMeter;
playSound() async{
player.play("2100.mp3");
}
void start() async {
//_noiseSubscription = _noiseMeter.noiseStream.listen(onData);
try {
_noiseSubscription = _noiseMeter.noiseStream.listen(onData);
} catch (exception) {
print(exception);
}
}
void onData(NoiseReading noiseReading) {
this.setState(() {
if (!this._isRecording) {
this._isRecording = true;
}
});
/// Do someting with the noiseReading object
print(noiseReading.toString());
}
void onError(PlatformException e) {
print(e.toString());
_isRecording = false;
}
void stopRecorder() async {
try {
if (_noiseSubscription != null) {
_noiseSubscription.cancel();
_noiseSubscription = null;
}
this.setState(() {
this._isRecording = false;
});
} catch (err) {
print('stopRecorder error: $err');
}
}
#override
void initState() {
// TODO: implement initState
super.initState();
//start();
_noiseMeter = new NoiseMeter(onError);
}
#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: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
// player.play("2100.mp3");
//
// player.clearCache();
playSound();
start();
},
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
Any help will be much appreciated.
This seems to be a known error for iOS 14+ devices.
On iOS 14 and higher, enable the Dart multicast DNS service in the
Debug version of your app to add debugging functionalities such as
hot-reload and DevTools via flutter attach.
Check out the documentation about "Local Network Privacy Permissions". From there, I suggest to follow the instructions on enabling the Dart multicast DNS service in the Debug version of your app.

Auto_route unable to use the generated file : no name parameter with the name 'reportsRouteUpdateToEngine'

i'm trying auto_route but i don't understand what i'm doing wrong.
Here is my router.dart :
#MaterialAutoRouter(
routes: <AutoRoute>[
// initial route is named "/"
MaterialRoute(page: HomeView, initial: true),
MaterialRoute(page: StartupView),
],
)
class $Router {}
And here is my main.dart
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
builder: ExtendedNavigator.builder(
router: Router(),
builder: (context, extendedNav) => Theme(
data: ThemeData(brightness: Brightness.dark),
child: extendedNav,
),
),
);
}
}
i've run
flutter packages pub run build_runner build
Then when i run myApp and then i get this error :
Error: No named parameter with the name 'reportsRouteUpdateToEngine'.
reportsRouteUpdateToEngine: true,
^^^^^^^^^^^^^^^^^^^^^^^^^^
I also tried without their extendedNav, just like this :
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
onGenerateRoute: Router(),
);
}
}
Still doesn't work.
Any help ?
The 0.6.9 version seems to work only with the latest flutter version (1.22).
My flutter version was outdated, i upgraded it and it works with 0.6.9.
For a version of Flutter less than 1.22 you need to specify this version in the pubspec.yaml file without the ^:
auto_route: 0.6.7

When assembleDebug Out of Memory error is thrown

So I'm new to flutter and dart.I've made multiple android apps and I am pretty familiar with coding but I just can't get to know flutter. I use Android Studio as Ide and when I try to compile my code , on the assembleDebug part, This error is thrown:
c:\b\s\w\ir\k\src\third_party\dart\runtime\vm\zone.cc: 54: error: Out
of memory.
version=2.4.0 (Wed Jun 19 11:53:45 2019 +0200) on "windows_x64"
thread=1336, isolate=main(0000029506C2CDE0)
pc 0x00007ff7b33d2b1b fp 0x000000d10cbfb0a0 Unknown symbol
-- End of DumpStackTrace
For now, I haven't done anything to fix the problem because I don't know why
main.dart
import 'package:flutter/material.dart';
import 'constants.dart';
import 'package:flutter_svg/flutter_svg.dart';
void main() {
runApp(UnitConverterApp());
}
//on create
class UnitConverterApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Distivity Todolist',
theme: Constants.getTheme(),
home: CategoryRoute(),
);
}
}
class CategoryRoute extends StatefulWidget {
const CategoryRoute();
#override
_CategoryRouteState createState() => _CategoryRouteState();
}
class _CategoryRouteState extends State<CategoryRoute> {
/// Function to call when a [Category] is tapped.
void _onCategoryTap() {
setState(() {
});
}
#override
Widget build(BuildContext context) {
return Center(
child: InkWell(
onTap: () => _onCategoryTap(),
child: SvgPicture.asset(
Constants.add,
semanticsLabel: 'ad'
),
)
);
}
}
constants.dart
import 'package:flutter/material.dart';
class Constants{
static ThemeData getTheme(){
return ThemeData(
primaryColor: colorSwatch,
);
}
static const primaryColor = 0xff4FB484;
static ColorSwatch colorSwatch = ColorSwatch(primaryColor, const<String,Color>{
"primary_color": Color(primaryColor),
"primary_dark":Color(0xff306D50),
"black_16": Color(0xff161616),
"black_20":Color(0xff202020),
"the_blackest":Color(0xff000000),
"color_white":Color(0xffF7F7F7),
"the_whitest":Color(0xffffffff)
});
static const String add = 'assets/add.svg';
}
pubspec.yaml
name: distivity_todolist
description: A new Flutter application.
https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
sdk: ">=2.1.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^0.1.2
dev_dependencies:
flutter_svg: 0.13.1
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
assets:
- assets/add.svg