Old iron remember to forward, Brother Mao will present more Flutter good articles~~~~
WeChat group ducafecat
b Station https://space.bilibili.com/404904528
original
https://medium.com/geekculture/build-a-camera-app-flutter-in-app-camera-825b829fe138
Code
https://github.com/jagrut-18/flutter_camera_app.git
reference
text
In many applications, we need users to upload pictures by clicking on them. For this, we can use the default camera application of the device, but what if we need to integrate an in-app camera? Well, this is also possible with Flutter. The team has developed a called camera https://pub.dev/packages/camera , which allows us to do this.
create project
First, install the camera package into the project by adding the following lines in the pubspec.yaml file.
camera: ^0.8.1+3
- IOS settings
This plugin requires IOS 10.0 or higher. Add the following lines in the Info.plist file to set the content.
<key>NSCameraUsageDescription</key>
<string>Can I use the camera please?</string>
<key>NSMicrophoneUsageDescription</key>
<string>Can I use the mic please?</string>
- Android Setup
Change the minimum version of Android sdk to 21 (or higher) in the Android/app/build.gradle file.
minSdkVersion 21
Now that our project setup is complete, we can start writing applications.
We will create two screens in the application.
1.CameraScreen ーThis screen will display the camera output and take pictures
2.GalleryScreen ーThis screen will display the captured pictures in a grid view.
Mount the camera
In order to display the camera preview, we need to load the camera first. To do this, go to the main function in the main.dart file and these lines above runApp.
WidgetsFlutterBinding.ensureInitialized(); //Ensure plugin services are initializedfinal cameras = await availableCameras(); //Get list of available cameras
Now that we have a list of cameras, we need to pass them to our camera/screen.
So, the camera will pass like this
After all this, this is what main.dart looks like.
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'camera_screen.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// Obtain a list of the available cameras on the device.
final cameras = await availableCameras();
runApp(MyApp(cameras: cameras));
}
class MyApp extends StatelessWidget {
final List<CameraDescription> cameras;
const MyApp({Key? key, required this.cameras}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Camera App',
home: CameraScreen(cameras: cameras),
);
}
}
CameraScreen
The layout of this screen is simple. At the top we will display the live camera preview and at the bottom there will be three buttons (swap cameras, capture and show gallery).
Create a stateful widget CameraScreen.
We will create four variables,
We must set selectedCamera = 0, starting from the rear camera. If the device has more than 1 camera, we can switch to it by changing this index.
Now let's create a method to initialize the selected camera.
In this method, we will pass the camera index to be initialized. Using the passed camera list, we will load the specific camera and resolution selection.
Using this method, we will initialize the rear camera in initState.
Don't forget to throw away the camera controller.
- Now let's build the UI.
In order to display CameraPreview, we will use the following code.
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 const Center(child: CircularProgressIndicator());
}
},
),
Okay, now we want to display three buttons in a row.
Switch/camera button
The first is to switch the camera icon button. Click this button and the camera should switch between front and rear.
For this, we will use the same initializeCamera method, but this time cameraIndex will be dynamic. cameraIndex The rear camera is 0, and the front camera is 1 (if there is a front camera).
Upon clicking, we will check if the device has multiple cameras, if not, we will display a snackbar with a message.
IconButton(
onPressed: () {
if (widget.cameras.length > 1) {
setState(() {
selectedCamera = selectedCamera == 0 ? 1 : 0;//Switch camera
initializeCamera(selectedCamera);
});
} else {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('No secondary camera found'),
duration: const Duration(seconds: 2),
));
}
},
icon: Icon(Icons.switch_camera_rounded, color: Colors.white),
),
Snap button
To show the capture button, I used a simple white circle with a radius of 60. After clicking, we will use the camera controller to take a photo and add it to the captureImages array.
GestureDetector(
onTap: () async {
await _initializeControllerFuture; //To make sure camera is initialized
var xFile = await _controller.takePicture();
setState(() {
capturedImages.add(File(xFile.path));
});
},
child: Container(
height: 60,
width: 60,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.white,
),
),
),
Show gallery button
This button is very simple, we will display the last picture taken from the capturedmages array, and when clicked, it will navigate to the GalleryScreen.
GestureDetector(
onTap: () {
if (capturedImages.isEmpty) return; //Return if no image
Navigator.push(context,
MaterialPageRoute(
builder: (context) => GalleryScreen(
images: capturedImages.reversed.toList())));
},
child: Container(
height: 60,
width: 60,
decoration: BoxDecoration(
border: Border.all(color: Colors.white),
image: capturedImages.isNotEmpty
? DecorationImage(image: FileImage(capturedImages.last), fit: BoxFit.cover)
: null,
),
),
),
As you can see, GalleryScreen accepts a list of captured images, so we can display them in the gridview. Let's complete this part to see how the application is running.
GalleryScreen
This is a very direct screen. Get a list of images and display them in the GridView.
import 'dart:io';
import 'package:flutter/material.dart';
class GalleryScreen extends StatelessWidget {
final List<File> images;
const GalleryScreen({Key? key, required this.images}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Gallery'),
),
body: GridView.count(
crossAxisCount: 3,
mainAxisSpacing: 2,
crossAxisSpacing: 2,
children: images
.map((image) => Image.file(image, fit: BoxFit.cover))
.toList(),
),
);
}
}
Final Product
After building the application, this is the final result.
Camera package can also capture video, you can use startVideoRecording, pauseVideoRecording and stopVideoRecording methods to capture https://pub.dev/packages/Camera.
This is the Github link of this project, I hope it helps you.
https://github.com/jagrut-18/flutter_camera_app.git
That's it, I hope you like it.
© Cat brother
Past
Open source
GetX Quick Start
https://github.com/ducafecat/getx_quick_start
News client
https://github.com/ducafecat/flutter_learn_news
strapi manual translation
WeChat discussion group ducafecat
Series collection
Translation
https://ducafecat.tech/categories/%E8%AF%91%E6%96%87/
Open source project
https://ducafecat.tech/categories/%E5%BC%80%E6%BA%90/
Dart programming language basics
https://space.bilibili.com/404904528/channel/detail?cid=111585
Getting started with Flutter zero foundation
https://space.bilibili.com/404904528/channel/detail?cid=123470
Flutter actual combat from scratch news client
https://space.bilibili.com/404904528/channel/detail?cid=106755
Flutter component development
https://space.bilibili.com/404904528/channel/detail?cid=144262
Flutter Bloc
https://space.bilibili.com/404904528/channel/detail?cid=177519
Flutter Getx4
https://space.bilibili.com/404904528/channel/detail?cid=177514
Docker Yapi
https://space.bilibili.com/404904528/channel/detail?cid=130578
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。