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
@boeledi, If you want to “lock” the device orientation and not allow it to change as the user rotates their phone, this was easily set as below,
// This did not work as requirement
void main() {
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
runApp(new MyApp());
}
You have to wait until
setPreferredOrientations
is done and then start the app
// This will works always for lock screen Orientation.
void main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
.then((_) {
runApp(new MyApp());
});
}
Calling SystemChrome.setPreferredOrientations()
doesn't work for me, and I had to change the Device Orientation
in the Xcode project as following:
Set the screenOrientation
attribute to portrait
for the main activity in the file android/app/src/main/AndroidManifest.xml
as following:
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());
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With