I would like to prevent my application from changing its orientation and force the layout to stick to \"portrait\".
In the main.dart, I put:
void mai
If you are editing this from the xcode interface, it will not be changed for ipad. For the ipad section, you must edit the info.plist file from the android studio. You can see in the array list like that "~ ipad". There are two sections available in info.plist, you have to manually edit it for both iphone and ipad.
For people, that they are reading this question now. The easiest way that I found and it worked on both android & ios devices.
void main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations(
[
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
],
).then((val) {
runApp(YourAppName());
});
}
Import package:flutter/services.dart
, then
Put the SystemChrome.setPreferredOrientations
inside the Widget build()
method.
Example:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
return new MaterialApp(...);
}
}
Update
This solution mightn't work for some IOS devices as mentioned in the updated flutter documentation on Oct 2019.
They Advise to fixed the orientation by setting UISupportedInterfaceOrientations in Info.plist like this
<array>
<string>UIInterfaceOrientationPortrait</string>
</array>
For more information https://github.com/flutter/flutter/issues/27235#issuecomment-508995063
Put the WidgetsFlutterBinding.ensureInitialized() else you will get an error while building.
import 'package:flutter/services.dart';
void main() async => {
WidgetsFlutterBinding.ensureInitialized(),
await SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitUp]), // To turn off landscape mode
runApp(MainApp())
};
setPreferredOrientation
returns a Future<void>
, so it is asynchronous. The most readable approach is to define main
as asynchronous:
Future<void> main() async {
await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
return runApp(new MyApp());
}
Below is the official example of the flutter team. https://github.com/flutter/samples/blob/master/veggieseasons/lib/main.dart
import 'package:flutter/services.dart' show DeviceOrientation, SystemChrome;
void main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
runApp(HomeScreen());
}