Как я могу повернуть свое приложение флаттера влево или вправо в зависимости от ориентации телефона пользователя? - PullRequest
0 голосов
/ 19 сентября 2019

Я заставил мое приложение перейти в альбомный режим при использовании

SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeRight,
      DeviceOrientation.landscapeLeft,
]);

Но я не могу заставить его поворачивать альбомную ориентацию вправо или влево, в зависимости от того, как пользователь держит телефон.

Я не хочу переходить от портрета к пейзажу, я просто хочу иметь возможность переходить к двум различным сторонам ландшафта, даже когда автоповорот отключен.

1 Ответ

0 голосов
/ 19 сентября 2019

Добавьте следующую зависимость в ваш файл pubsec.yaml

    dependencies:
  native_device_orientation: ^0.2.0

Выполните следующую команду или терминал, чтобы получить пакет зависимостей

flutter pub get

Импортируйте следующий класс как

import 'package:native_device_orientation/native_device_orientation.dart';

А вот и остальные примеры кода.

import 'package:flutter/material.dart';
import 'package:native_device_orientation/native_device_orientation.dart';

void main() => runApp(new MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool useSensor = false;

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
          appBar: new AppBar(
            title: new Text('Native Orientation example app'),
            actions: <Widget>[Switch(value: useSensor, onChanged: (val) => setState(() => useSensor = val))],
          ),
// encapsulating your Screen UI with NativeDeviceOrientationReader is must.
              body: NativeDeviceOrientationReader(
                builder: (context) {
                  NativeDeviceOrientation orientation = NativeDeviceOrientationReader.orientation(context);
                  print("Received new orientation: $orientation");
                  return Center(child: Text('Native Orientation: $orientation\n'));
                },
                useSensor: useSensor,
              ),
              floatingActionButton: Builder(
                builder: (context) {
                  return Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      FloatingActionButton(
                        child: Text("Sensor"),
                        onPressed: () async {
                          NativeDeviceOrientation orientation =
                          await NativeDeviceOrientationCommunicator().orientation(useSensor: true);
                          Scaffold.of(context).showSnackBar(
                            SnackBar(
                              content: Text("Native Orientation read: $orientation"),
                              duration: Duration(milliseconds: 500),
                            ),
                          );
                        },
                      ),
                      SizedBox(height: 10),
                      FloatingActionButton(
                        child: Text("UI"),
                        onPressed: () async {
                          NativeDeviceOrientation orientation =
                              await NativeDeviceOrientationCommunicator().orientation(useSensor: false);
                          Scaffold.of(context).showSnackBar(
                            SnackBar(
                              content: Text("Native Orientation read: $orientation"),
                              duration: Duration(milliseconds: 500),
                            ),
                          );
                        },
                      ),
                    ],
                  );
                },
              )),
        );
      }
    }
...