How to take picture and save in device gallery in Flutter

In this Google Flutter code snippet example, we are going to learn How to take picture and save in device gallery in flutter

You can copy and adopt this source code example tp your flutter project easily without issues.

add this code to your pubspec.yaml file

camera: ^0.5.2+1

Create a camera_save_img.dart file (use any name of your choice) and add this code:

import 'dart:async';

import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';

class CamSaveImg extends StatefulWidget {
  @override
  _CamSaveImgState createState() => _CamSaveImgState();
}

class _CamSaveImgState extends State<CamSaveImg> {
  CameraController _controller;
  Future<void> _initCamFuture;

  @override
  void initState() {
    super.initState();
    _initApp();
  }

  _initApp() async {
    final cameras = await availableCameras();
    final firstCam = cameras.first;

    _controller = CameraController(
      firstCam,
      ResolutionPreset.medium,
    );

    _initCamFuture = _controller.initialize();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Save Picture")),
      body: FutureBuilder<void>(
        future: _initCamFuture,
        builder: (context, snapshot) {
          
            return CameraPreview(_controller);
          
        },
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.camera_alt),
        onPressed: () async {
          try {
            await _initCamFuture;

            final path = join(
              (await getTemporaryDirectory()).path,
              '${DateTime.now()}.png',
            );

            await _controller.takePicture(path);
          } catch (e) {
            print(e);
          }
        },
      ),
    );
  }
}

In your main.dart file (main entry point of the app), add this:

import 'package:inducesmile/camera_save_img.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Code Snippets',
      theme: new ThemeData(primarySwatch: Colors.red),
      home: new CamSaveImg(),
    );
  }
}

If you have any questions or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment