avatarJC.log

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

4981

Abstract

we will pass the camera index that we want to initialize. Using the list of cameras passed, we will load the specific camera with resolution of our choice.</p><p id="d9b1">Using this method, we will initialize the rear camera in <code>initState</code>.</p><figure id="ac52"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*oWxm0p_gCn9R1S6MnoPE7g.png"><figcaption>initState</figcaption></figure><p id="f9c8">And do not forget to dispose the Camera Controller.</p><figure id="af06"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*VYmzVrA-t5YFoagfBw7nGg.png"><figcaption>dispose</figcaption></figure><p id="7055"><b>Now let’s build the UI.</b></p><p id="0dca">To show the CameraPreview we will use the following code. Until the camera loads, we will show <code>CircularProgressIndicator</code>.</p><div id="dcb2"><pre><span class="hljs-built_in">FutureBuilder</span><<span class="hljs-type">void</span>>( future: _initializeControllerFuture, builder: (context, snapshot) { <span class="hljs-keyword">if</span> (snapshot.connectionState == ConnectionState.done) { <span class="hljs-comment">// If the Future is complete, display the preview.</span> <span class="hljs-keyword">return</span> <span class="hljs-built_in">CameraPreview</span>(_controller); } <span class="hljs-keyword">else</span> { <span class="hljs-comment">// Otherwise, display a loading indicator.</span> <span class="hljs-keyword">return</span> <span class="hljs-type">const</span> <span class="hljs-built_in">Center</span>(child: <span class="hljs-built_in">CircularProgressIndicator</span>()); } }, ),</pre></div><p id="74b9">Okay, now we have to show three buttons in a <code>row</code>.</p><h1 id="156a">SwitchCamera Button</h1><p id="0cfd">First is the switch camera icon button. On tapping this, the camera should switch between front and rear.</p><p id="ab9d">For that, we will use the same <code>initializeCamera</code> method, but this time the <code>cameraIndex</code> will be dynamic. <code>cameraIndex</code> will be <code>0</code> for rear camera and <code>1</code> for front camera (if there is front camera).</p><p id="4329">On click, we will check whether the devices has more than one cameras, if not we will show a snackbar with a message.</p><div id="4560"><pre><span class="hljs-title function_ invoke__">IconButton</span>( <span class="hljs-attr">onPressed</span>: () { <span class="hljs-keyword">if</span> (widget.cameras.length > <span class="hljs-number">1</span>) { <span class="hljs-title function_ invoke__">setState</span>(() { selectedCamera = selectedCamera == <span class="hljs-number">0</span> ? <span class="hljs-number">1</span> : <span class="hljs-number">0</span>;<span class="hljs-comment">//Switch camera</span> <span class="hljs-title function_ invoke__">initializeCamera</span>(selectedCamera); }); } <span class="hljs-keyword">else</span> { ScaffoldMessenger.<span class="hljs-title function_ invoke__">of</span>(context).<span class="hljs-title function_ invoke__">showSnackBar</span>(<span class="hljs-title function_ invoke__">SnackBar</span>( <span class="hljs-attr">content</span>: <span class="hljs-title function_ invoke__">Text</span>(<span class="hljs-string">'No secondary camera found'</span>), <span class="hljs-attr">duration</span>: <span class="hljs-keyword">const</span> <span class="hljs-title function_ invoke__">Duration</span>(<span class="hljs-attr">seconds</span>: <span class="hljs-number">2</span>), )); } }, icon: <span class="hljs-title function_ invoke__">Icon</span>(Icons.switch_camera_rounded, <span class="hljs-attr">color</span>: Colors.white), ),</pre></div><h1 id="6751">Capture Button</h1><p id="d4c0">To show a capture button, I have used a simple white circle with 60 radius. When clicked, we will use the camera controller to take a picture and add it to the <code>captureImages</code> array.</p><div id="9e87"><pre>GestureDetector( <span class="hljs-symbol"> onTap:</span> () <span class="hljs-title class_">async</span> <span class="hljs-punctuation">{</span> await _initializeControllerF<span class="hljs-attr">uture</span><span class="hljs-punctuation">;</span> <span class="hljs-comment">//To make sure camera is initialized</span> var xF<span class="hljs-attr">ile</span> <span class="hljs-operator">=</span> await _controller.takePicture()<span class="hljs-punctuation">;</span> setState(() <span class="hljs-punctuation">{</span> capturedImages.add(File(xFile.path))<span class="hljs-punctuation">;</span> <span class="hljs-punctuation">}</span>)<span class="hljs-punctuation">;</span> <span class="hljs-punctuation">}</span>, <span class="hljs-symbol"> child:</span> Container( <span class="hljs-symbol"> height:</span> <span class="hljs-number">60</span>, <span class="hljs-symbol"> width:</span> <span class="hljs-number">60</span>, <

Options

span class="hljs-symbol"> decoration:</span> BoxDecoration( <span class="hljs-symbol"> shape:</span> BoxShape.circle, <span class="hljs-symbol"> color:</span> Colors.white, ), ), ),</pre></div><h1 id="fdea">Show Gallery Button</h1><p id="ef8f">This button is quite simple, we will show the <b>last</b> image taken from the <code>capturedImages</code> array and when clicked, it will navigate to the <code>GalleryScreen</code>.</p><div id="ce97"><pre><span class="hljs-selector-tag">GestureDetector</span>( <span class="hljs-attribute">onTap</span>: () { <span class="hljs-selector-tag">if</span> (capturedImages.isEmpty) <span class="hljs-selector-tag">return</span>; <span class="hljs-comment">//Return if no image</span> <span class="hljs-selector-tag">Navigator</span><span class="hljs-selector-class">.push</span>(context, <span class="hljs-built_in">MaterialPageRoute</span>( <span class="hljs-attribute">builder</span>: (context) => <span class="hljs-built_in">GalleryScreen</span>( <span class="hljs-attribute">images</span>: capturedImages.reversed.<span class="hljs-built_in">toList</span>()))); }, <span class="hljs-selector-tag">child</span>: <span class="hljs-selector-tag">Container</span>( <span class="hljs-attribute">height</span>: <span class="hljs-number">60</span>, <span class="hljs-attribute">width</span>: <span class="hljs-number">60</span>, <span class="hljs-attribute">decoration</span>: <span class="hljs-built_in">BoxDecoration</span>( <span class="hljs-attribute">border</span>: Border.<span class="hljs-built_in">all</span>(<span class="hljs-attribute">color</span>: Colors.white), <span class="hljs-attribute">image</span>: capturedImages.isNotEmpty ? <span class="hljs-built_in">DecorationImage</span>(<span class="hljs-attribute">image</span>: <span class="hljs-built_in">FileImage</span>(capturedImages.last), <span class="hljs-attribute">fit</span>: BoxFit.cover) : null, ), ), ),</pre></div><p id="b2e6">As you can see, the <code>GalleryScreen</code> accepts list of images captured so that we can show them in a gridview. Let’s finish that part to see the app in action.</p><h1 id="de88">GalleryScreen</h1><p id="4aba">This is screen is very straighforward. Get the list of images and show them in a <code>GridView</code>.</p> <figure id="2e79"> <div> <div>

            <iframe class="gist-iframe" src="/gist/jagrut-18/655416e05c123cc0e1b6da305c1dc773.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
          </div>
        </div>
    </figure></iframe></div></div></figure><p id="8e6f"><b>One more thing</b>

If you liked this story, also check out this new story I posted recently.</p><div id="2e87" class="link-block"> <a href="https://javascript.plainenglish.io/flutter-audio-player-using-just-audio-734792562384"> <div> <div> <h2>Flutter: Audio Player Using just_audio</h2> <div><h3>Hello everyone, today we will see how to integrate an audio player in a Flutter app. This demo app will have a player…</h3></div> <div><p>javascript.plainenglish.io</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*gMt2S1_tzTrWey_vx-DZfA.png)"></div> </div> </div> </a> </div><h1 id="3b07">Final Product</h1><p id="69ca">After building the app, here is the final result.</p><figure id="add0"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*qlKAcT6rfNIL2L9Gg80VOw.png"><figcaption></figcaption></figure><p id="dd43">The Camera Package (<a href="https://pub.dev/packages/camera">https://pub.dev/packages/camera</a>) is also capable of capturing videos. You can use <code>startVideoRecording</code>, <code>pauseVideoRecording</code> and <code>stopVideoRecording</code> methods for that.</p><p id="9d73">Here is the Github link for the project. Hope you find it helpful.</p><div id="99c5" class="link-block"> <a href="https://github.com/jagrut-18/flutter_camera_app.git"> <div> <div> <h2>jagrut-18/flutter_camera_app</h2> <div><h3>A new Flutter project. This project is a starting point for a Flutter application. A few resources to get you started…</h3></div> <div><p>github.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*eu6PClh_qJPdsuaZ)"></div> </div> </div> </a> </div><p id="f839">That’s it for this one. Hope you like it.</p><p id="e3e1">Thank you for reading until this point. Make sure to leave a comment for any suggestions and 👏 for this story.</p></article></body>

Build a Camera App : Flutter In-App Camera

In many apps we need users to upload images by clicking a picture. For that, we can use the default camera app of the device but what if we need to integrate an in-app camera? Well, that is also possible with flutter. The flutter team has developed a package called camera (https://pub.dev/packages/camera) which will let us do exactly this.

Let’s see how can we achieve this by a simple example.

Setting up the project

First of all, install the camera package into your project by adding the following line into pubspec.yaml file.

camera: ^0.8.1+3

— IOS Setup

IOS 10.0 or higher is required for this plugin. Add the following lines in the Info.plist file to set things up.

<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 Android sdk version to 21 (or higher) in your android/app/build.gradle file.

minSdkVersion 21

Now that our project set up is complete, we can start coding the app.

We will create two screens in the app. 1. CameraScreen — This screen will show the camera output and take pictures 2. GalleryScreen — This screen will show captured pictures in a gridview.

Loading Cameras

To show the camera preview, we will need to load the cameras first. For that, go to the main function in main.dart file and these lines above runApp.

WidgetsFlutterBinding.ensureInitialized(); //Ensure plugin services are initialized
final cameras = await availableCameras(); //Get list of available cameras

Now that we have list of cameras, we need to pass those to our CameraScreen.

So, cameras will be passed like this

Passing cameras list

After all this, this is how main.dart looks.

CameraScreen

The layout of this screen is simple. On top we will show live camera preview and at bottom there will be three buttons (Switch camera, Capture and Show Gallery).

Create a stateful widget called CameraScreen.

We will create four variables,

We have to set selectedCamera = 0, to start with the rear camera. If the device has more than 1 camera then we can switch to it by changing this index.

Now let’s create a method to initialize selected camera.

In this method, we will pass the camera index that we want to initialize. Using the list of cameras passed, we will load the specific camera with resolution of our choice.

Using this method, we will initialize the rear camera in initState.

initState

And do not forget to dispose the Camera Controller.

dispose

Now let’s build the UI.

To show the CameraPreview we will use the following code. Until the camera loads, we will show CircularProgressIndicator.

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 have to show three buttons in a row.

SwitchCamera Button

First is the switch camera icon button. On tapping this, the camera should switch between front and rear.

For that, we will use the same initializeCamera method, but this time the cameraIndex will be dynamic. cameraIndex will be 0 for rear camera and 1 for front camera (if there is front camera).

On click, we will check whether the devices has more than one cameras, if not we will show 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),
),

Capture Button

To show a capture button, I have used a simple white circle with 60 radius. When clicked, we will use the camera controller to take a picture 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 quite simple, we will show the last image taken from the capturedImages 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, the GalleryScreen accepts list of images captured so that we can show them in a gridview. Let’s finish that part to see the app in action.

GalleryScreen

This is screen is very straighforward. Get the list of images and show them in a GridView.

One more thing If you liked this story, also check out this new story I posted recently.

Final Product

After building the app, here is the final result.

The Camera Package (https://pub.dev/packages/camera) is also capable of capturing videos. You can use startVideoRecording, pauseVideoRecording and stopVideoRecording methods for that.

Here is the Github link for the project. Hope you find it helpful.

That’s it for this one. Hope you like it.

Thank you for reading until this point. Make sure to leave a comment for any suggestions and 👏 for this story.

App Development
Android
iOS
Flutter App Development
Flutter
Recommended from ReadMedium