Flutter how to disable landscape orientation? - flutter

I want to disable the landscape mode. I tried to allow only portrait mode using following code. But it is not working with my physical device. How to solve this?
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
runApp(MyApp());
}

You need to paste the code in Widget build(). Consider this answer for more details
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
return new MaterialApp(...);
}
}

Related

Flutter Images load slow

I have added a Video to visualize my problem better: https://streamable.com/wdhna2
The problem is that my images load slowly, even I added a precache method and a splash screen. On first boot, the problem isn't that big, maybe because of the precache.
here I'm implementing the precache method:
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
loadImage(context); <--- Method call
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
and here is my precache method (just a snipped, not for all pictures):
import 'package:flutter/material.dart';
void loadImage(context){
precacheImage(const AssetImage("assets/widgetsImages/bmi.jpg"), context);
precacheImage(const AssetImage("assets/widgetsImages/calc.webp"), context);
precacheImage(const AssetImage("assets/widgetsImages/chat.webp"), context);
}
I also tried to add a splash screen with the flutter_native_splash package, but this wouldn't fix the problem that the images load slowly after I close and reopen the app, without clearing my RAM. Anyway, here is the code for that:
Future<void> main() async {
WidgetsBinding widgetsBinding = WidgetsFlutterBinding.ensureInitialized();
FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);
and the end of the splashscreen when the first window opens:
class _NutriWidgetState extends State<NutriWidget> {
#override
void initState() {
super.initState();
FlutterNativeSplash.remove();
}
Do you have an idea how I could load the images faster? Do I do something wrong?
try
image.assets("assets/widgetsImages/bmi.jpg")
think you can not call directly into the widget builder
you have to wrap it into Scaffolds
or return your method not call this
return loadImage(context)

Why does my program crash when I add a text field?

My code is very simple:
import 'package:flutter/material.dart';
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(title:"title", home: Scaffold(body: TextField()));
}
}
void main() {
runApp(MyApp());
}
No matter how I try to include the text field, the program just crushes.
I'm compiling to web, maybe that's related to the problem?
Edit: So that's awkward. But the code seems to work perfectly fine now...
Though the following code still crashes after adding the text field:
import 'package:flutter/material.dart';
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(title:"title", home: Scaffold(body:
Row(children: [
Column(children: [
TextField()
])
]
)));
}
}
void main() {
runApp(MyApp());
}
This happens, because there is no width constraint to the TextField.
In your case, wrapping the column in an Expanded widget should fix the problem.
See the flutter documentation for more info and solutions to this problem: https://flutter.dev/docs/testing/common-errors#an-inputdecoratorcannot-have-an-unbounded-width

Flutter dynamic screen rotation

What is the best way to dynamically do screen rotation in Flutter for few of the screens and not affect to other screens?
So i tried two ways, with mixins. (This way stackoverflow ). It works initially, for the first enter and leave screen, but when I do re-run again some of screen which should be landscape again, it's fixed in portrait and thats all, until i re-run the app.
And tried directly, with setting preferred orientation. (This way stackoverflow This way mess-up whole app even if i just unlock rotation on build/initState (tried both) on one screen, and lock it on same screen on dispose.
For example, i need camera screen rotated with whole UI, and i have screen to edit the image, and i need that screen in the portrait, and there problems shows up.
UPDATE: So here is the link with code with mixins try. I created mixin which enables rotation in that screen, and on dispose, lock rotation again. CODE
And code here:
mixin RotationEnabledStatefulModeMixin<T extends StatefulWidget> on
State<T> {
#override
Widget build(BuildContext context) {
_enableRotation();
return null;
}
#override
void dispose() {
_portraitModeOnly();
print("RotationEnabledStatefulModeMixin -> disposed!");
}
}
void _portraitModeOnly() {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
}
void _enableRotation() {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight,
]);
}
//this is screen where i need landscape only
class TakePictureScreen extends StatefulWidget {
final CameraDescription camera;
TakePictureScreen(
{Key key, #required this.camera, this.report, this.sectionIndex})
: super(key: key);
#override
TakePictureScreenState createState() => TakePictureScreenState();
}
class TakePictureScreenState extends State<TakePictureScreen> with
RotationEnabledStatefulModeMixin<TakePictureScreen>{
CameraController _controller;
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
super.build(context);
}
#override
void dispose() {
_controller.dispose();
super.dispose();
}
}

Flutter app leaves blank space at the top of the screen when removing system overlays

When removing system overlays with SystemChrome.setEnabledSystemUIOverlays([]) the app does not expand to fill the screen.
Complete main.dart file:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setEnabledSystemUIOverlays([]);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Container(
color: Colors.red,
),
);
}
}
Without SystemChrome.setEnabledSystemUIOverlays([]):
Flutter version: 1.22.2
I'm unable to reproduce with Flutter 1.22(stable) but in https://github.com/flutter/flutter/issues/14432 people seem to have had good results with
setting Scaffold.resizeToAvoidBottomPadding to true.
You can also try to update Flutter and/or changing channels. Perhaps even trying on a physical device.

Flutter: How to set and lock screen orientation on-demand

On one of my flutter pages, I need the screen to set to landscape mode and lock it so it can't rotate into portrait mode, but only on the one page. So need a way to enable this function on-the-fly. Anyone know how to do this?
I would like it to rotate landscape-left or landscape-right, just not into portrait mode.
First import the services package:
import 'package:flutter/services.dart';
This will give you access to the SystemChrome class, which "Controls specific aspects of the operating system's graphical interface and how it interacts with the application."
When you load the Widget, do something like this:
#override
void initState(){
super.initState();
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeRight,
DeviceOrientation.landscapeLeft,
]);
}
then when I leave the page, put it back to normal like this:
#override
dispose(){
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeRight,
DeviceOrientation.landscapeLeft,
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
super.dispose();
}
I would use a simple mixin to lock phone in portrait. The following solution locks the entire app in portrait or sets specific screens to portrait while keeping rotation elsewere.
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
/// Forces portrait-only mode application-wide
/// Use this Mixin on the main app widget i.e. app.dart
/// Flutter's 'App' has to extend Stateless widget.
///
/// Call `super.build(context)` in the main build() method
/// to enable portrait only mode
mixin PortraitModeMixin on StatelessWidget {
#override
Widget build(BuildContext context) {
_portraitModeOnly();
return null;
}
}
/// Forces portrait-only mode on a specific screen
/// Use this Mixin in the specific screen you want to
/// block to portrait only mode.
///
/// Call `super.build(context)` in the State's build() method
/// and `super.dispose();` in the State's dispose() method
mixin PortraitStatefulModeMixin<T extends StatefulWidget> on State<T> {
#override
Widget build(BuildContext context) {
_portraitModeOnly();
return null;
}
#override
void dispose() {
_enableRotation();
super.dispose();
}
}
/// blocks rotation; sets orientation to: portrait
void _portraitModeOnly() {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
}
void _enableRotation() {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight,
]);
}
To block rotation in the entire app implement PortraitModeMixin in the main App widget. Remember to call super.build(context) in Widget build(BuildContext context) method.
/// Main App widget
class App extends StatelessWidget with PortraitModeMixin {
const App();
#override
Widget build(BuildContext context) {
super.build(context);
return CupertinoApp(
title: 'Flutter Demo',
theme: CupertinoThemeData(),
home: Text("Block screen rotation example"),
);
}
}
To block rotation in a specific screen implement PortraitStatefulModeMixin<SampleScreen> in the specific screen's state. Remember to call super.build(context) in the State's build() method and super.dispose() in dispose() method. If your screen is a StatelessWidget - simply repeat the App's solution (previous example) i.e. use PortraitModeMixin.
/// Specific screen
class SampleScreen extends StatefulWidget {
SampleScreen() : super();
#override
State<StatefulWidget> createState() => _SampleScreenState();
}
class _SampleScreenState extends State<SampleScreen>
with PortraitStatefulModeMixin<SampleScreen> {
#override
Widget build(BuildContext context) {
super.build(context);
return Text("Flutter - Block screen rotation example");
}
#override
void dispose() {
super.dispose();
}
}
Mixins with such syntax work from Dart 2.1
First, Lock the entire app orientation to Portrait mode.
//Do this in main.dart
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
.then((_) {
runApp(MyApp());
});
Second, Go the specific screen where you want to change the orientation.
#override
void initState() {
super.initState();
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.landscapeRight,
DeviceOrientation.landscapeLeft
]);
}
#override
void dispose() {
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
super.dispose();
}
For using SystemChrome you will have to add 'package:flutter/services.dart'
void main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp, DeviceOrientation.portraitDown])
.then((_) {
runApp(new MyApp());
});
}
import services.dart package and add following code to lock device orientation to portraitUp mode:
import 'package:flutter/services.dart';
main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
runApp(MyHomePage());
}
Sometimes it could not work due to null info about orientation.
You can use it simply like this:
import services.dart
void main() {
SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitUp]
)
.then((_) {
runApp(new MyApp());
});
}
// wait for settings screen orientation after initiating app and -> then lock orientation
Important for iOS.
Enable the orientation in in info.plist file. for Example
Steps
Set the orientation in main.dart file. In my case, My application is only support for portrait except the one screen so i need to set the portrait mode at first time. for Example
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp,DeviceOrientation.portraitDown,]);
Add the following code in that screen which you need to rotate.
void initState() {
super.initState();
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeRight,
DeviceOrientation.landscapeLeft,
]);
}
#override
dispose(){
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
super.dispose();
}
Simple way to lock screen orientation in whole app
Add import 'package:flutter/services.dart'; to the start of main.dart file.
Create SystemChrome.setPreferredOrientations(); method to disable Screen rotation in Widget build area of MyApp class just before the return part.
Specify the orientation using [DeviceOrientation.<orientation-type>] in arguments of the method.
Use one of the following in place of <orientation-type> :
portraitUp
portraitDown
landscapeLeft
landscapeRight
Example Code:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' ;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
]);
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Screen Orientation"),
),
body: Container(
),
),
);
}
}
import services.dart and your void main function should be like:
void main(){
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitUp, DeviceOrientation.portraitDown])
.then((_){
runApp(MyApp());
}
);
}
You can use orientation_helper for this https://pub.dev/packages/orientation_helper . It’s main goal is to set orientation for each screen in an app.
For those who prefer to use hooks
import 'package:flutter/services.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
useOrientation(List<DeviceOrientation> orientations) {
useEffect(
() {
SystemChrome.setPreferredOrientations(orientations);
return () {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight,
]);
};
},
);
}
Use it like:
class MyWidget extends HookWidget {
void build(BuildContext context) {
useOrientation([DeviceOrientation.portraitUp]);
return Container();
}
}
In AndroidManifest file in main folder under activity tag set android:screenOrientation = "portrait"
<activity android:windowSoftInputMode="adjustResize" android:screenOrientation = "portrait">
Set the preferred orientation in the flutter.
// import this package
import 'package:flutter/services.dart';
// Lock the orientation to Portrait Only
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
.then((value) => runApp(MyApp()));
You can also add Preferred Orientations in the setPreferredOrientations list like [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]
Below are the orientation you can set:
/// If the device shows its boot logo in portrait, then the boot logo is shown
/// in [portraitUp]. Otherwise, the device shows its boot logo in landscape
/// and this orientation is obtained by rotating the device 90 degrees
/// clockwise from its boot orientation.
portraitUp,
/// The orientation that is 90 degrees clockwise from [portraitUp].
///
/// If the device shows its boot logo in landscape, then the boot logo is
/// shown in [landscapeLeft].
landscapeLeft,
/// The orientation that is 180 degrees from [portraitUp].
portraitDown,
/// The orientation that is 90 degrees counterclockwise from [portraitUp].
landscapeRight,
Ref: https://greymag.medium.com/flutter-orientation-lock-portrait-only-c98910ebd769
In GetX, you need to use GetBuilder like this example:
final Controller ctrl = Get.find();
GetBuilder<Controller>(
initState: (_) => ctrl.setLandscape(),
dispose: (_) => ctrl.setPortrait(),
builder: (code) => Container(
padding: const EdgeInsets.zero,
alignment: Alignment.Center,
child: const SizedBox(),
),
),
In Controller file:
class Controller extends GetxController {
RxBool isLandscape = false.obs;
Future<void> setLandscape() async {
if (isLandscape.isTrue) {
await SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeLeft]);
update();
}
}
Future<void> setPortrait() async {
if (isLandscape.isFalse) {
await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
update();
}
}
}
I hope this solution will answer developers who use GetX as their main state management. Good luck, bro! God blesses you all.