Blog Details

img
Development

Gallery Access and Camera in Flutter

Spoke Right / 31 Oct, 2023

We can add images from the gallery using the image_picker package in Flutter. For this, you’ll need to use your real device.

Follow the below steps to display the images from the gallery:

Step 1:  Create a new flutter application:

flutter create 

Step 2: Now, delete the code from the main.dart file to add your own code.

Step 3: Add the dependency to your pubspec.yaml file:

pubspec

Step 4: Use the below code in the main.dart file :

main.dart

  • Dart




import 'dart:io';


import 'package:flutter/material.dart';

import 'package:image_picker/image_picker.dart';


void main() {

  runApp(const MyApp());

}


class MyApp extends StatelessWidget {

  const MyApp({super.key});


  @override

  Widget build(BuildContext context) {

    return MaterialApp(

      theme: ThemeData(primaryColor: Colors.green),

      home: const GalleryAccess(),

      debugShowCheckedModeBanner: false,

    );

  }

}


class GalleryAccess extends StatefulWidget {

  const GalleryAccess({super.key});


  @override

  State createState() => _GalleryAccessState();

}


class _GalleryAccessState extends State {

  File? galleryFile;

  final picker = ImagePicker();

  @override

  Widget build(BuildContext context) {

    //display image selected from gallery


    return Scaffold(

      appBar: AppBar(

        title: const Text('Gallery and Camera Access'),

        backgroundColor: Colors.green,

        actions: const [],

      ),

      body: Builder(

        builder: (BuildContext context) {

          return Center(

            child: Column(

              mainAxisAlignment: MainAxisAlignment.center,

              children: [

                ElevatedButton(

                  style: ButtonStyle(

                      backgroundColor: MaterialStateProperty.all(Colors.green)),

                  child: const Text('Select Image from Gallery and Camera'),

                  onPressed: () {

                    _showPicker(context: context);

                  },

                ),

                const SizedBox(

                  height: 20,

                ),

                SizedBox(

                  height: 200.0,

                  width: 300.0,

                  child: galleryFile == null

                      ? const Center(child: Text('Sorry nothing selected!!'))

                      : Center(child: Image.file(galleryFile!)),

                ),

                const Padding(

                  padding: EdgeInsets.symmetric(vertical: 18.0),

                  child: Text(

                    "GFG",

                    textScaleFactor: 3,

                    style: TextStyle(color: Colors.green),

                  ),

                )

              ],

            ),

          );

        },

      ),

    );

  }


  void _showPicker({

    required BuildContext context,

  }) {

    showModalBottomSheet(

      context: context,

      builder: (BuildContext context) {

        return SafeArea(

          child: Wrap(

            children: [

              ListTile(

                leading: const Icon(Icons.photo_library),

                title: const Text('Photo Library'),

                onTap: () {

                  getImage(ImageSource.gallery);

                  Navigator.of(context).pop();

                },

              ),

              ListTile(

                leading: const Icon(Icons.photo_camera),

                title: const Text('Camera'),

                onTap: () {

                  getImage(ImageSource.camera);

                  Navigator.of(context).pop();

                },

              ),

            ],

          ),

        );

      },

    );

  }


  Future getImage(

    ImageSource img,

  ) async {

    final pickedFile = await picker.pickImage(source: img);

    XFile? xfilePick = pickedFile;

    setState(

      () {

        if (xfilePick != null) {

          galleryFile = File(pickedFile!.path);

        } else {

          ScaffoldMessenger.of(context).showSnackBar(// is this context <<<

              const SnackBar(content: Text('Nothing is selected')));

        }

      },

    );

  }

}

Output:

When no image is selected, it will result:

interface

When the button is pressed, it will ask for accessing photos, media, and files on your device as shown below:

When the permission is given to access photos and any image is selected from the gallery, it will be displayed on the screen as shown below:

Explanation:

  • import image_picker package in main.dart file.
  • For selecting gallery and camera to select image for that we have _showPicker() this function.
  • For selecting images and set state the image getImage() and await for gallery image.
  • the image will be displayed after loaded.

0 comments

Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /usr/local/lib/php/extensions/no-debug-non-zts-20210902/imagick.so (/usr/local/lib/php/extensions/no-debug-non-zts-20210902/imagick.so: cannot open shared object file: No such file or directory), /usr/local/lib/php/extensions/no-debug-non-zts-20210902/imagick.so.so (/usr/local/lib/php/extensions/no-debug-non-zts-20210902/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0