blob: e2f1ff931e42c2d402b30c2448d065958f28ca49 [file] [log] [blame]
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:camera/camera.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
/// A widget showing a live camera preview.
class CameraPreview extends StatelessWidget {
/// Creates a preview widget for the given camera controller.
const CameraPreview(this.controller, {this.child});
/// The controller for the camera that the preview is shown for.
final CameraController controller;
/// A widget to overlay on top of the camera preview
final Widget? child;
@override
Widget build(BuildContext context) {
return controller.value.isInitialized
? AspectRatio(
aspectRatio: _isLandscape()
? controller.value.aspectRatio
: (1 / controller.value.aspectRatio),
child: Stack(
fit: StackFit.expand,
children: [
_wrapInRotatedBox(child: controller.buildPreview()),
child ?? Container(),
],
),
)
: Container();
}
Widget _wrapInRotatedBox({required Widget child}) {
if (defaultTargetPlatform != TargetPlatform.android) {
return child;
}
return RotatedBox(
quarterTurns: _getQuarterTurns(),
child: child,
);
}
bool _isLandscape() {
return [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]
.contains(_getApplicableOrientation());
}
int _getQuarterTurns() {
Map<DeviceOrientation, int> turns = {
DeviceOrientation.portraitUp: 0,
DeviceOrientation.landscapeLeft: 1,
DeviceOrientation.portraitDown: 2,
DeviceOrientation.landscapeRight: 3,
};
return turns[_getApplicableOrientation()]!;
}
DeviceOrientation _getApplicableOrientation() {
return controller.value.isRecordingVideo
? controller.value.recordingOrientation!
: (controller.value.lockedCaptureOrientation ??
controller.value.deviceOrientation);
}
}