- Install
- Set up an editor
- Test drive
- Write your first Flutter app, part 1
- Learn more
- Flutter for Android developers
- Flutter for iOS developers
- Flutter for React Native developers
- Flutter for web developers
- Flutter for Xamarin.Forms developers
- Introduction to declarative UI
- Cookbook
- Codelabs
- Tutorials
- User interface
- Introduction to widgets
- Layouts in Flutter
- Layout tutorial
- Dealing with box constraints
- Adding interactivity to your Flutter app
- Adding assets and images
- Navigation & routing
- Introduction to animations
- Animations overview
- Animations tutorial
- Hero Animations
- Staggered Animations
- Advanced UI
- Slivers
- Taps, drags, and other gestures
- Widget catalog
- Data & backend
- State management
- State management
- Start thinking declaratively
- Differentiate between ephemeral state and app state
- Simple app state management
- List of state management approaches
- JSON and serialization
- Firebase
- Accessibility & internationalization
- Accessibility
- Internationalizing Flutter apps
- Platform integration
- Writing custom platform-specific code
- Packages & plugins
- Using packages
- Developing packages & plugins
- Background processes
- Tools & techniques
- Android Studio / IntelliJ
- Visual Studio Code
- Upgrading Flutter
- Hot reload
- Code formatting
- Debugging Flutter apps
- Using OEM debuggers
- Flutter's build modes
- Testing Flutter apps
- Performance best practices
- Flutter performance profiling
- Creating flavors for Flutter
- Preparing an Android App for Release
- Preparing an iOS App for Release
- Continuous Delivery using fastlane with Flutter
- Bootstrap into Dart
- Inside Flutter
- Platform specific behaviors and adaptations
- Technical Overview
- Technical videos
- FAQ
- Flutter widget index
- Install
- Windows install
- MacOS install
- Linux install
- Set up an editor
- Write your first Flutter app, part 1
- Learn more
- Cupertino (iOS-style) widgets
- Layout widgets
- Animation and motion widgets
- Retrieve the value of a text field
- Basic widgets
- Material Components widgets
- Animate the properties of a Container
- Fade a Widget in and out
- Add a Drawer to a screen
- Displaying SnackBars
- Exporting fonts from a package
- Updating the UI based on orientation
- Using Themes to share colors and font styles
- Using custom fonts
- Working with Tabs
- Building a form with validation
- Create and style a text field
- Focus on a Text Field
- Handling changes to a text field
- Retrieve the value of a text field
- Adding Material Touch Ripples
- Handling Taps
- Implement Swipe to Dismiss
- Display images from the internet
- Fade in images with a placeholder
- Working with cached images
- Basic List
- Create a horizontal list
- Creating a Grid List
- Creating lists with different types of items
- Place a floating app bar above a list
- Working with long lists
- Report errors to a service
- Animating a Widget across screens
- Navigate to a new screen and back
- Navigate with named routes
- Pass arguments to a named route
- Return data from a screen
- Send data to a new screen
- Fetch data from the internet
- Making authenticated requests
- Parsing JSON in the background
- Working with WebSockets
- Persist data with SQLite
- Reading and Writing Files
- Storing key-value data on disk
- Play and pause a video
- Take a picture using the Camera
- An introduction to integration testing
- Performance profiling
- Scrolling
- An introduction to unit testing
- Mock dependencies using Mockito
- An introduction to widget testing
- Finding widgets
- Tapping, dragging and entering text
- Development
- Introduction to widgets
- Layout tutorial
- Dealing with box constraints
- Adding interactivity to your Flutter app
- Adding assets and images
- Navigation & routing
- Navigate to a new screen and back
- Send data to a new screen
- Return data from a screen
- Navigate with named routes
- Animating a Widget across screens
- AnimatedList
- Sample App Catalog
- Animations overview
- Animations tutorial
- Staggered Animations
- Slivers
- Taps, drags, and other gestures
- Accessibility widgets
- Assets, images, and icon widgets
- Async widgets
- Input widgets
- Interaction model widgets
- Painting and effect widgets
- Scrolling widgets
- Styling widgets
- Text widgets
- State management
- Start thinking declaratively
- Differentiate between ephemeral state and app state
- Simple app state management
- List of state management approaches
- JSON and serialization
- Accessibility
- Internationalizing Flutter apps
- Writing custom platform-specific code
- Using packages
- Fetch data from the internet
- Developing packages & plugins
- Background processes
- Android Studio / IntelliJ
- Set up an editor
- Flutter inspector
- Creating Useful Bug Reports
- Visual Studio Code
- Set up an editor
- Upgrading Flutter
- Hot reload
- Code formatting
Take a picture using the Camera
Many apps require working with the device’s cameras to take photos and videos. Flutter provides the camera
plugin for this purpose. The camera
plugin provides tools to get a list of the available cameras, display a preview coming from a specific camera, and take photos or videos.
This recipe demonstrates how to use the camera
plugin to display a preview, take a photo, and display it.
Directions
- Add the required dependencies
- Get a list of the available cameras
- Create and initialize the
CameraController
- Use a
CameraPreview
to display the camera’s feed - Take a picture with the
CameraController
- Display the picture with an
Image
Widget
1. Add the required dependencies
To complete this recipe, you need to add three dependencies to your app:
camera
- Provides tools to work with the cameras on devicepath_provider
- Finds the correct paths to store imagespath
- Creates paths that work on any platform
dependencies:
flutter:
sdk: flutter
camera:
path_provider:
path:
2. Get a list of the available cameras
Next, you can get a list of available cameras using the camera
plugin.
// 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;
3. Create and initialize the CameraController
Once you have a camera to work with, you need to create and initialize a CameraController
. This process establishes a connection to the device’s camera that allows you to control the camera and display a preview of the camera’s feed.
To achieve this, please:
- Create a
StatefulWidget
with a companionState
class - Add a variable to the
State
class to store theCameraController
- Add a variable to the
State
class to store theFuture
returned fromCameraController.initialize
- Create and initialize the controller in the
initState
method - Dispose of the controller in the
dispose
method
// A screen that takes in a list of Cameras and the Directory to store images.
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> {
// Add two variables to the state class to store the CameraController and
// the Future
CameraController _controller;
Future<void> _initializeControllerFuture;
@override
void initState() {
super.initState();
// In order to display the current output from the Camera, you need to
// 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, you need to initialize the controller. This returns a Future
_initializeControllerFuture = _controller.initialize();
}
@override
void dispose() {
// Make sure to dispose of the controller when the Widget is disposed
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
// Fill this out in the next steps
}
}
4. Use a CameraPreview
to display the camera’s feed
Next, you can use the CameraPreview
Widget from the camera
package to display a preview of the camera’s feed.
Remember: You must wait until the controller has finished initializing before working with the camera. Therefore, you must wait for the _initializeControllerFuture
created in the previous step to complete before showing a CameraPreview
.
You can use a FutureBuilder
for exactly this purpose.
// You must 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
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());
}
},
)
5. Take a picture with the CameraController
You can also use the CameraController
to take pictures using the takePicture
method. In this example, create a FloatingActionButton
that takes a picture using the CameraController
when a user taps on the button.
Saving a picture requires 3 steps:
- Ensure the camera is initialized
- Construct a path that defines where the picture should be saved
- Use the controller to take a picture and save the result to the path
It is good practice to wrap these operations in a try / catch
block in order to handle any errors that might occur.
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 the camera is initialized
await _initializeControllerFuture;
// Construct the path where the image should be saved using the path
// package.
final path = join(
// In this example, 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);
} catch (e) {
// If an error occurs, log the error to the console.
print(e);
}
},
)
6. Display the picture with an Image
Widget
If you take the picture successfully, you can then display the saved picture using an Image
widget. In this case, the picture is stored as a file on the device.
Therefore, you must provide a File
to the Image.file
constructor. You can create an instance of the File
class by passing in the path you created in the previous step.
Image.file(File('path/to/my/picture.png'))
Complete Example
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 {
// 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();
// In order to display the current output from the Camera, you need to
// 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, you need to initialize the controller. This returns a Future
_initializeControllerFuture = _controller.initialize();
}
@override
void dispose() {
// Make sure to 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')),
// You must 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 the camera is initialized
await _initializeControllerFuture;
// Construct the path where the image should be saved using the path
// package.
final path = join(
// In this example, 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)),
);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论