В настоящее время я пытаюсь закодировать приложение камеры, которое захватывает изображение и отображает его через отдельный виджет. Для этого я использую документы Flutter здесь. Это полный код.
import 'dart:async';
import 'dart:io';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:path/path.dart' show join;
import 'package:path_provider/path_provider.dart';
Future<void> main() async {
// Ensure that plugin services are initialized so that `availableCameras()`
// can be called before `runApp()`
WidgetsFlutterBinding.ensureInitialized();
// Obtain a list of the available cameras on the device.
final cameras = await availableCameras();
// Get a specific camera from the list of available cameras.
final firstCamera = cameras.first;
runApp(
MaterialApp(
theme: ThemeData.dark(),
home: TakePictureScreen(
// Pass the appropriate camera to the TakePictureScreen widget.
camera: firstCamera,
),
),
);
}
// A screen that allows users to take a picture using a given camera.
class TakePictureScreen extends StatefulWidget {
final CameraDescription camera;
const TakePictureScreen({
Key key,
@required this.camera,
}) : super(key: key);
@override
TakePictureScreenState createState() => TakePictureScreenState();
}
class TakePictureScreenState extends State<TakePictureScreen> {
CameraController _controller;
Future<void> _initializeControllerFuture;
@override
void initState() {
super.initState();
// To display the current output from the Camera,
// create a CameraController.
_controller = CameraController(
// Get a specific camera from the list of available cameras.
widget.camera,
// Define the resolution to use.
ResolutionPreset.medium,
);
// Next, initialize the controller. This returns a Future.
_initializeControllerFuture = _controller.initialize();
}
@override
void dispose() {
// Dispose of the controller when the widget is disposed.
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Take a picture')),
// Wait until the controller is initialized before displaying the
// camera preview. Use a FutureBuilder to display a loading spinner
// until the controller has finished initializing.
body: FutureBuilder<void>(
future: _initializeControllerFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
// If the Future is complete, display the preview.
return CameraPreview(_controller);
} else {
// Otherwise, display a loading indicator.
return Center(child: CircularProgressIndicator());
}
},
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.camera_alt),
// Provide an onPressed callback.
onPressed: () async {
// Take the Picture in a try / catch block. If anything goes wrong,
// catch the error.
try {
// Ensure that the camera is initialized.
await _initializeControllerFuture;
// Construct the path where the image should be saved using the
// pattern package.
final path = join(
// Store the picture in the temp directory.
// Find the temp directory using the `path_provider` plugin.
(await getTemporaryDirectory()).path,
'${DateTime.now()}.png',
);
// Attempt to take a picture and log where it's been saved.
await _controller.takePicture(path);
// If the picture was taken, display it on a new screen.
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DisplayPictureScreen(imagePath: path),
),
);
} catch (e) {
// If an error occurs, log the error to the console.
print(e);
}
},
),
);
}
}
// A widget that displays the picture taken by the user.
class DisplayPictureScreen extends StatelessWidget {
final String imagePath;
const DisplayPictureScreen({Key key, this.imagePath}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Display the Picture')),
// The image is stored as a file on the device. Use the `Image.file`
// constructor with the given path to display the image.
body: Image.file(File(imagePath)),
);
}
}
Теперь функция takePicture()
должна принимать path
в качестве аргумента, а это не так.
Как мне обработать эту ошибку, чтобы правильно сохранить изображение, а затем получить путь к изображению для его отображения?
Заранее спасибо!
Ваш код кажется правильным. Какие типы ошибок вы встречаете?
После первого нажатия кнопки сделать снимок ничего не происходит. Когда я нажимаю ее второй раз, я получаю эту ошибку: I/flutter (11480): CameraException (предыдущий захват еще не вернулся. TakePicture был вызван до возврата предыдущего захвата.)
Похоже, что функция takePicture() никогда не выполняется полностью.
Вы работаете на реальном устройстве или на эмуляторе?
Я запускаю его на эмуляторе.
Это может быть ваша проблема. Вам уже было предложено предоставить разрешение на использование камеры?
Да, когда я впервые протестировал приложение, оно запросило у меня разрешение на использование камеры. Попробую на реальном устройстве.
На реальном устройстве тоже не работает..
Ваш код будет работать с этой версией плагина камеры.
dependencies:
camera: 0.5.8+17
Начиная с версии 0.6.x, у takePicture нет параметра. Если вы хотите запустить его с последней версией плагина, взгляните на текущий пример .
Да, это решило мою проблему! Так же спасибо за пример с самой новой версией, буду разбираться!
Я использую версию камеры ^0.7.0, и приложение аварийно завершает работу при вызове функции «Controller.takePicture()». В чем проблема и решение? Пожалуйста, предложите. Спасибо.
как я. я использую последнюю версию. но у меня был стоп-кадр при переключении камеры с задней камеры на переднюю. также я делюсь своей проблемой по моей проблеме в stackoverflow. наверное, можно посмотреть по этой ссылке stackoverflow.com/questions/68867327/…
Немного поздно, но, возможно, это поможет другим использовать последнюю версию камеры. Метод контроллера -> takePicture() возвращает объект XFile, а объект XFile имеет метод saveTo()
XFile picture = await controller.takePicture();
picture.saveTo(filePath);
Опубликовать весь код своей Страницы?