Flutter orientation lock: portrait only
In Flutter we have SystemChrome.setPreferredOrientation() (see documentation) to define preferred orientation. Exactly this method you can find in all those articles about setup orientation in Flutter. Let’s see how we can use it:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
// We need to call it manually,
// because we going to call setPreferredOrientations()
// before the runApp() call
WidgetsFlutterBinding.ensureInitialized();
// Than we setup preferred orientations,
// and only after it finished we run our app
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
.then((value) => runApp(MyApp()));
}
iOS
Open project in Xcode (ios/Runner.xcworkspace)
, choose Runner
in the project navigator, select Target Runner
and on Tab General
in section Deployment Info
we can setup Device Orientation:
Also, we can do it manually without opening Xcode at all — just edit ios/Runner/Info.plist
. Open it as a text file, find key UISupportedInterfaceOrientation
and leave only desired values:
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
</array>
Android
To define orientation for Android
we need to edit ApplicationManifest
. Open android/app/src/main/AndroidManifest.xml
and add an attribute screenOrientation for a main
activity:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.orientation_lock_example">
<application ...>
<activity
android:name=".MainActivity"
android:screenOrientation="portrait"
...
/>
...
</activity>
...
</application>
</manifest>
And that’s all. Here is the repository with an example app:
Hope this was helpful.
'package:flutter/services.dart'
, then maybe it's a bug: github.com/flutter/flutter/issues/13238SystemChrome.setPreferredOrientations
returns asynchronously, so seems likerunApp
should be enclosed in athen
.main()
async and putawait
in front ofSystemChrome...