Flutter: Camera and Path provider
Coding the Camera Screen
It’s time to look at all the Dart files one by one.
Open the main.dart file:
import 'package:flutter/material.dart';
import 'camerascreen/camera_screen.dart';
class CameraApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: CameraScreen(),
);
}
}
void main() => runApp(CameraApp());
CameraApp
is the root widget. This is the entry point for your app. Its responsibility is to launch the CameraScreen
widget where you will see the camera preview.
Next, open the camera_screen.dart file. This is a StatefulWidget
, because you will be adding the feature to toggle between the front and back camera (changing the state of the camera). If you go through the file you will find some TODO’s which you will be addressing soon.
Going step by step, first add four properties to the _CameraScreenState
class as shown below:
class _CameraScreenState extends State {
CameraController controller;
List cameras;
int selectedCameraIdx;
String imagePath;
You might see a red squiggly error line under CameraController
. If not, that’s because the needed import is already in the starter project file. But if so, you need to import the camera
package to make the error go away. Click on the line and press option+return on macOS or Alt+Enter on PC. You will see a menu popup:
Choose the import option to add the necessary import.
You must be curious to know about these four properties you just added:
-
CameraController controller
: This class is responsible for establishing a connection to the device’s camera. -
List cameras
: This will hold a list of the cameras available on the device. Normally, the size of the list will be 2 i.e. a front and back camera. The0
index is for the back camera and the1
index for the front camera. -
selectedCameraIdx
: This will hold the current camera index that the user has selected. -
imagePath
: This will hold the path of the image which you will create using the camera.
Next, override the initState()
method and add the following code to it:
@override
void initState() {
super.initState();
// 1
availableCameras().then((availableCameras) {
cameras = availableCameras;
if (cameras.length > 0) {
setState(() {
// 2
selectedCameraIdx = 0;
});
_initCameraController(cameras[selectedCameraIdx]).then((void v) {});
}else{
print("No camera available");
}
}).catchError((err) {
// 3
print('Error: $err.code\nError Message: $err.message');
});
}
Displaying the Camera Preview
From this point you’ll need to be on a physical device. Run the project and you should see the following screen:
Amazing! You’ve just integrated the camera feature into your app!
But as you can see, there is no way to switch between the front and back camera, and if you press the capture button nothing happens. You’ll implement those features next.
Comments
Post a Comment