Setting Flutter Orientation Conditionally

08/10/2019

I’ve been working on an app I wanted to allow iPads to auto-rotate while keeping iPhones in portrait only. Normally in iOS, you have to subclass the top-most view controller to get access to shouldAutorotate. Since my app is 100% Flutter and I didn’t want to mess with the original setup I came up with the snippet below and added it to my AppDelegate.swift.

extension FlutterViewController {
    open override var shouldAutorotate: Bool {
        return UIDevice.current.model.lowercased().contains("ipad")
    }
}

Swift extension’s are a very cool feature that allows you to extend the functionality of a class without the need to subclass it. Above I took full advantage of this by extending the FlutterViewController which is the default Flutter implementation for iOS. Then I override shouldAutorotate. This tells the OS to only allow rotation if the current device is an iPad. This small piece of code works great for my use case and I don’t have to pull in another dependency.

Below is what it could look like if you wanted to keep iPad in landscape mode while iPhones in portrait.

extension FlutterViewController {
    open override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return UIDevice.current.model.lowercased().contains("ipad") ? .landscape : .portrait
    }
    open override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return UIDevice.current.model.lowercased().contains("ipad") ? .landscapeLeft : .portrait
    }
    open override var shouldAutorotate: Bool {
        return UIDevice.current.model.lowercased().contains("ipad")
    }
}

If you need more fine-grained controls and cross-platform support, check out auto_orientation. This small package allows you to set orientation dynamically. This is also a great option if you are looking to force orientations changes programmatically.