Я бы использовал простой mixin до блокировки телефона в портретном .Следующее решение блокирует все приложение в портретной ориентации или устанавливает конкретные экраны в портретную ориентацию, сохраняя при этом вращение в другом месте.
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();
}
}
/// 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,
]);
}
В вращение блока во всем приложении внедрение PortraitModeMixin
в главном App
виджете.Не забудьте вызвать super.build(context)
в методе Widget build(BuildContext context)
.
/// 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"),
);
}
}
В поворот блока на определенном экране реализовать PortraitStatefulModeMixin<SampleScreen>
в определенном состоянии экрана.Не забудьте вызвать super.build(context)
в методе State build()
и super.dispose()
в dispose()
методе.Если ваш экран представляет собой StatelessWidget - просто повторите решение приложения (предыдущий пример), т.е. используйте 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();
}
}
Миксины с таким синтаксисом работают с Dart 2.1