Flutter禁止手机横屏的简单实现方法
作者:Becomin'' Charles 时间:2022-12-06 19:56:34
在一些特定的 App 里,我们不希望手机横屏的时候,App 发生旋转,比如微信,企业微信都是这样的。
代码可以这样设定:
import 'package:flutter/services.dart';
void main() async => {
WidgetsFlutterBinding.ensureInitialized();
await SystemChrome.setPreferredOrientations(
[
DeviceOrientation.portraitUp, // 竖屏 Portrait 模式
DeviceOrientation.portraitDown,
// DeviceOrientation.landscapeLeft, // 横屏 Landscape 模式
// DeviceOrientation.landscapeRight,
],
);
runApp(MainApp());
};
在 main 函数里,像上面那样设定,就可以做到全局禁用横屏模式了。
不过,在企业微信里,我发现,并不是彻底禁用了横屏模式,如果我在企业微信内部打开了一个网页,这种场景下,就是可以横屏过来用的。也就是,WebView 的场景下,我是可以横屏的,但是在其他界面下不可以横屏。这要怎么设置呢?
@override
void initState() {
super.initState();
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight,
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
}
@override
void dispose() {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
super.dispose();
}
像这样,设置到一个 StatefulWidget 的 initState 和 dispose 里面就可以了。比如在我的代码里,我把 WebView 专门封装了一个页面,叫 WebPage,这样设定后,当用户进入网页的时候,可以横屏,但是退回后,就会强制恢复竖屏。
参考:http://kmanong.top/kmn/qxw/form/article?id=2735&cate=93
参考:https://stackoverflow.com/questions/49418332/flutter-how-to-prevent-device-orientation-changes-and-force-portrait
来源:https://sexywp.com/flutter-disable-landscape-mode.htm
标签:flutter,禁止,横屏
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Android带进度的圆形进度条
2023-08-05 21:47:18
![](https://img.aspxhome.com/file/2023/8/86748_0s.jpg)
散列表的原理与Java实现方法详解
2023-06-06 06:46:29
Java系统的高并发解决方法详解
2021-08-23 08:39:50
Mybatis-plus实现主键自增和自动注入时间的示例代码
2022-11-05 00:22:51
详解在spring boot中消息推送系统设计与实现
2023-05-28 04:17:00
![](https://img.aspxhome.com/file/2023/2/74902_0s.jpg)
使用注解@Recover优化丑陋的循环详解
2021-08-05 15:11:13
![](https://img.aspxhome.com/file/2023/0/80880_0s.png)
JavaMail实现邮件发送的方法
2023-08-18 06:37:38
Java集合遍历实现方法及泛型通配
2022-02-26 13:55:54
![](https://img.aspxhome.com/file/2023/9/71189_0s.png)
基于Spring的注解@Qualifier小结
2022-12-20 23:17:50
Mybatis关联查询结果集对象嵌套的具体使用
2021-07-12 22:09:18
详解Android 多级联动控件实现思路讨论
2021-10-10 21:45:53
![](https://img.aspxhome.com/file/2023/7/137577_0s.gif)
解析Android 8.1平台SystemUI 导航栏加载流程
2023-06-23 15:21:21
spring boot线上日志级别动态调整的配置步骤
2022-09-19 01:57:45
![](https://img.aspxhome.com/file/2023/2/94312_0s.png)
Spring整合Mybatis思路梳理总结
2022-04-26 03:56:12
struts2拦截器_动力节点Java学院整理
2023-06-11 10:11:36
![](https://img.aspxhome.com/file/2023/2/78242_0s.png)
Java实现超大Excel文件解析(XSSF,SXSSF,easyExcel)
2023-11-27 11:02:17
![](https://img.aspxhome.com/file/2023/3/60113_0s.png)
JAVA字符串拼接常见方法汇总
2021-11-13 03:11:31
Android RecyclerView实现下拉刷新和上拉加载
2023-07-05 21:50:38
![](https://img.aspxhome.com/file/2023/7/139007_0s.gif)
Java实现图形界面计算器
2023-06-05 11:53:23
![](https://img.aspxhome.com/file/2023/7/65757_0s.jpg)
Android单点触控实现图片平移、缩放、旋转功能
2022-08-18 04:16:52
![](https://img.aspxhome.com/file/2023/4/123324_0s.png)