Error When Forcing Portrait Orientation in Flutter - flutter

I am trying to force my Flutter app to only use Portrait mode. My main() method looks like this.
void main() {
SystemChrome.setSystemUIOverlayStyle(uiOverlayStyle);
SystemChrome.setPreferredOrientations(ALLOWED_ORIENTATIONS)
.then((_) => runApp(MyApp()));
}
Here is the definition of ALLOWED_ORIENTATIONS:
const List<DeviceOrientation> ALLOWED_ORIENTATIONS = [
DeviceOrientation.portraitUp
];
I just separated all the settings and such to another file to make modifying them later on easier.
When I run this code, I get the following error.
[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception:
ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized.
If you're running an application and need to access the binary messenger before `runApp()`
has been called (for example, during plugin initialization), then you need to explicitly
call the `WidgetsFlutterBinding.ensureInitialized()` first.
It looks like there is some race condition that's failing. I am just not sure what is causing it. Removing the SystemChrome.setPreferredOrientations() line makes the app compile as expected. So, I am thinking the error has something to do with that line.
Any advice?

Like the error says
If you're running an application and need to access the binary
messenger before runApp() has been called (for example, during
plugin initialization), then you need to explicitly call the
WidgetsFlutterBinding.ensureInitialized() first.
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setSystemUIOverlayStyle(uiOverlayStyle);
await SystemChrome.setPreferredOrientations(ALLOWED_ORIENTATIONS);
runApp(MyApp());
}

Related

Flutter release app crashing and showing gray screen

I am getting a crash on some android devices when running my Flutter app.
I have been able to debug a release version of the app and this is the only debug output:
W/FlutterJNI(27448): FlutterJNI.loadLibrary called more than once
W/FlutterJNI(27448): FlutterJNI.prefetchDefaultFontManager called more than once
W/FlutterJNI(27448): FlutterJNI.init called more than once
I donĀ“t know where should I begin to look for the reason of the issue.
The device is showing a gray screen and stops working.
Wherever you create the firebaseMessagingBackgroundHandler, annotate it with #pragma('vm:entry-point') like this:
#pragma('vm:entry-point')
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
}
The reason is explained here:
https://github.com/firebase/flutterfire/blob/master/packages/firebase_messaging/firebase_messaging/example/lib/main.dart#L46

Flutter imageCache.clear(); error messages

How do I put imageCache.clear(); into my Flutter app? Five of my six images are loading but one refusing to load. I tried flutter clean and restarting Android Studio. When I do this at the top of the program:
import 'package:flutter/material.dart';
imageCache.clear();
I get this error message:
lib/main.dart:2:19: Error: Expected a function body or '=>'.
Try adding {}.
imageCache.clear();
I tried this
imageCache.clear() {}
but that got a different error message.
You probably put the function in the wrong place.
You can put in the initState
void initState() {
super.initState();
imageCache.clear();
}
or wherever a function should be not where a widget should be.

Flutter web build - blank page and stops on web_entrypoint.dart file

I'm trying to build a Flutter web fr my app project.
After passing "Flutter Create ." and trying to run in Chrome it shows a blank page and stops on the web_entrypoint.dart file.
Anyone knows what could be wrong?
perhaps you want to remove the Future<void> before main
Future<void> main() async{} //<--- remove Future<void>
// do
void main() async{
/* body */
}

clear shared preferences from myBackgroundMessageHandler

I want to clear shared preferences when I send a FCM message and app is in background. Inside myBackgroundMessageHandler method I am calling a method to clear them.
static Future<dynamic> myBackgroundMessageHandler(
Map<String, dynamic> message) {
clearPreferences();
}
static void clearPreferences() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.clear();
}
I am getting the following error:
Unhandled Exception: MissingPluginException(No implementation found
for method getAll on channel plugins.flutter.io/shared_preferences)
step 1)
go to Application.kt/Application.java (in my case is kotlin)
step 2)
add these line into Application class (in kotlin)
if (!registry!!.hasPlugin("io.flutter.plugins.sharedpreferences")) {
SharedPreferencesPlugin.registerWith(registry!!.registrarFor("io.flutter.plugins.sharedpreferences.SharedPreferencesPlugin"));
}
remember import this as well
import io.flutter.plugins.sharedpreferences.SharedPreferencesPlugin
step 3)
run flutter clean -> flutter get -> uninstall your app
The code is completely fine.
Just restart your emulator. If you didn't do a full restart by closing the emulator and open it up again, this error can propably occur, because it doesnt have the newly added plugins.
Add SharedPreferences.setMockInitialValues({}) to your code before the runApp() function inside the main function of Flutter App.
this fixed the error for me

What is WidgetsFlutterBinding and how it is being used in Flutter app?

When and how we use it?
How it works?
WidgetsFlutterBinding
You have to use it, in this way:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
https://flutter.dev/docs/resources/architectural-overview#architectural-layers
The WidgetFlutterBinding is used to interact with the Flutter engine. Firebase.initializeApp() needs to call native code to initialize Firebase, and since the plugin needs to use platform channels to call the native code, which is done asynchronously therefore you have to call ensureInitialized() to make sure that you have an instance of the WidgetsBinding.
Answerd By https://stackoverflow.com/users/7015400/peter-haddad
Answer Link https://stackoverflow.com/a/63873689
WidgetsBinding.ensureInitialized() This initialised communication between the Dart Layer and Flutter Engine.
We need to call this method if we need the binding to be initialised before calling [runApp]. Flutter cannot directly interact with flutter engine until and unless binding is established.
Example 1: Shows Firebase platform initialisation between flutter and native code, which Firestore class do internally.
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firestore.initializeApp();
runApp(
...
)
}
OR
Example 2: Shows device orientation changes before even app starts, for this also we need to established binding connection.
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown
]);
runApp(
...
)
}
Internally, WidgetsBinding.ensureInitialized() supports various binding likes GestureBinding, SchedulerBinding, ServicesBinding, PaintingBinding, SemanticsBinding, RendererBinding, WidgetsBinding
ServicesBinding listens for platform messages and directs them to the handler for incoming messages (BinaryMessenger).
PaintingBinding is responsible for binding to the painting library.
RenderBinding binds the render tree to the Flutter engine.
WidgetBinding binds the widget tree to the Flutter engine.
SchedulerBinding is the scheduler for running immediate tasks.
SemanticsBinding binds the semantics layer and the Flutter engine.
GestureBinding is a binding for the gesture subsystem.