【问题标题】:Error When Forcing Portrait Orientation in Flutter在 Flutter 中强制纵向方向时出错
【发布时间】:2020-05-11 06:14:03
【问题描述】:

我试图强制我的 Flutter 应用仅使用肖像模式。我的 main() 方法如下所示。

void main() {
  SystemChrome.setSystemUIOverlayStyle(uiOverlayStyle);
  SystemChrome.setPreferredOrientations(ALLOWED_ORIENTATIONS)
  .then((_) => runApp(MyApp()));
}

这是 ALLOWED_ORIENTATIONS 的定义:

const List<DeviceOrientation> ALLOWED_ORIENTATIONS = [
  DeviceOrientation.portraitUp
];

我只是将所有设置等分离到另一个文件中,以便以后更轻松地进行修改。

当我运行此代码时,我收到以下错误。

[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception:
ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized.
If you're running an application and need to access the binary messenger before `runApp()`
has been called (for example, during plugin initialization), then you need to explicitly
call the `WidgetsFlutterBinding.ensureInitialized()` first.

看起来有一些竞争条件失败了。我只是不确定是什么原因造成的。删除 SystemChrome.setPreferredOrientations() 行会使应用程序按预期编译。所以,我认为该错误与该行有关。

有什么建议吗?

【问题讨论】:

标签: flutter


【解决方案1】:

就像错误所说的那样

如果您正在运行应用程序并需要访问二进制文件 runApp() 之前的 messenger 已被调用(例如,在 插件初始化),那么你需要显式调用 WidgetsFlutterBinding.ensureInitialized()先。

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  SystemChrome.setSystemUIOverlayStyle(uiOverlayStyle);
  await SystemChrome.setPreferredOrientations(ALLOWED_ORIENTATIONS);

  runApp(MyApp());  
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-30
    • 2018-08-31
    • 1970-01-01
    • 2012-07-21
    • 1970-01-01
    • 2013-09-28
    • 2020-10-24
    • 1970-01-01
    相关资源
    最近更新 更多