Image Picker use in Flutter 2024: Capture Images with Camera or Choose from Gallery in Android & IOS

Hamza Asif
6 min readSep 8, 2024

--

Capturing images using a camera and using it in your Flutter applications can be tricky at times but the process is quite simple.

So in this story, I will teach you to get images from the gallery or capture images using a camera in Flutter and then display images beautifully in our Application.

Note: Flutter Machine Learning & AI Courses

If you want to build Machine Learning and AI based smart Flutter apps then check our Mobile Machine Learning courses on udemy. Avail 92% off with coupon code “MOBILEMLAI” only for limited time

  1. Flutter & AI: Build Image & Art Generation Flutter App
  2. Flutter & OCR — Build Document Scanner Clone in Flutter
  3. Face Recognition and Detection in Flutter — The 2024 Guide
  4. FlutterFlow for Beginners: Build “No Code” Apps in 2024
  5. Flutter & Google Gemini — Build Chatbots and Assistants
  6. Flutter & ML : Train Tensorflow Lite models for Flutter Apps
  7. Train Object Detection & Image Classify models for Flutter
  8. Machine Learning use in Flutter — The 2024 Guide
  9. Train Image Classification Models & Build Smart Flutter Apps 2024
  10. Build Gallery App Clone in Flutter With Circle To Search Feature

So Let’s start

Open your Android Studio or Visual Studio and create a new Flutter project. After that create a simple GUI in which we will have an Image widget and two buttons. So you can simply replace the content of main.dart with the below code.

import 'dart:io';

import 'package:flutter/material.dart';

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({super.key});

// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: const MyHomePage(title: 'Image picker'),
);
}
}

class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
File? _image;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
_image != null
? Image.file(
_image!,
width: 250,
height: 250,
)
: Icon(
Icons.image,
size: 200,
),
Row(
children: [
ElevatedButton(
onPressed: () {},
child: Icon(
Icons.image_search,
size: 50,
color: Colors.white,
),
style:
ElevatedButton.styleFrom(backgroundColor: Colors.black),
),
ElevatedButton(
onPressed: () {},
child: Icon(
Icons.camera,
size: 50,
color: Colors.white,
),
style:
ElevatedButton.styleFrom(backgroundColor: Colors.black),
)
],mainAxisAlignment: MainAxisAlignment.spaceEvenly,
)
],
),
),
);
}
}

Now you can run the app and will be able to see a screen like that

So in the GUI, we have two ElevatedButtons. One is for choosing images from the gallery and the second one is for capturing images from the camera. After that, we have declared a File variable with the name _image, and that variable will be used to store the image that we will choose or capture. Above these buttons, we have a condition that if _image is null then display an Icon widget, and if it's not null then display the image stored in that variable.

Now’s time to add the library. So open pub.dev and search for a library named image picker. In the search results click on the library and select the installing section. There you will find the dependency so simply copy it and put it in your pubspec.yaml file in the dependencies section

dependencies:
flutter:
sdk: flutter


# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.8
image_picker: ^1.1.2 #add this line

Android & IOS Setup

After that, we need to do some setup for Android & IOS. So for IOS, we need to specify the reason why our app wants to access pictures of the gallery or why we want to access the camera. So to do that, expand the IOS folder and then the Runner folder and you will find a file named info.plist. So open the file and in the <dict> tag paste these line

<key>NSPhotoLibraryUsageDescription</key>
<string>write reason for accessing the gallery</string>
<key>NSCameraUsageDescription</key>
<string>write reason for accessing the camera</string>

Now in the string tags you can change the text with the reason that why your app wants to access gallery or camera.

For Android, we don’t need to do anything.

Choosing Images From Gallery

So to use the library declare and initialize an object of type Imagepicker above the build method.

final ImagePicker picker = ImagePicker();

Now create a method named pickImageFromGallery and add the code to choose images from gallery inside that method. So to choose images from gallery we will use the imagepicker object that we created and we will call its pickImage method. In that method, we will specify the image source to gallery. So add this method above the build method.

pickImageFromGallery() async{
final XFile? photo = await picker.pickImage(source: ImageSource.gallery);
if(photo != null){
setState(() {
_image = File(photo.path);
});
}
}

After that call this method when our first ElevatedButton will be pressed. So our button code will look like that

ElevatedButton(
onPressed: () {
pickImageFromGallery();
},
child: Icon(
Icons.image_search,
size: 50,
color: Colors.white,
),
style:
ElevatedButton.styleFrom(backgroundColor: Colors.black),
),

So when when user will click on the button this method will be executed and gallery will be opened and we can select the image. Once the user selects the image we will get that image in the form of XFile object named as photo. Now after verifying that our photo variable is not null we are getting the path of the image and creating a File object and then assigning it to our _image variable. And as we are doint it in a setState block so it means where ever we are using this _image variable our GUI will be updated. And we are using this variable inside an Image widget. So now our image will be displayed on screen.

So let’s install the app and test it.

Capture images with Camera

To capture images the process is also quite easy. You can simply make a copy of pickImageFromGallery method and change its name to like “captureImages”. Now inside it just change the image source to camera. So the method will look like that

captureImages() async{
final XFile? photo = await picker.pickImage(source: ImageSource.camera);
if(photo != null){
setState(() {
_image = File(photo.path);
});
}
}

Now simply call this method when second ElevatedButton will be pressed. And that’s it. You can simple run the app and click on second button and the camera will be launched. And once you will capture the image, it will be displayed on screen.

So after completing the app our whole code will look like that

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});

// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Flutter Demo',
home: MyHomePage(title: 'Image picker'),
);
}
}

class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
File? _image;
final ImagePicker picker = ImagePicker();

pickImageFromGallery() async{
final XFile? photo = await picker.pickImage(source: ImageSource.gallery);
if(photo != null){
setState(() {
_image = File(photo.path);
});
}
}

captureImages() async{
final XFile? photo = await picker.pickImage(source: ImageSource.camera);
if(photo != null){
setState(() {
_image = File(photo.path);
});
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
_image != null
? Image.file(
_image!,
width: 250,
height: 250,
)
: const Icon(
Icons.image,
size: 200,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton(
onPressed: () {
pickImageFromGallery();
},
style:
ElevatedButton.styleFrom(backgroundColor: Colors.black),
child: const Icon(
Icons.image_search,
size: 50,
color: Colors.white,
),
),
ElevatedButton(
onPressed: () {
captureImages();
},
style:
ElevatedButton.styleFrom(backgroundColor: Colors.black),
child: const Icon(
Icons.camera,
size: 50,
color: Colors.white,
),
)
],
)
],
),
),
);
}
}

Note: 92% off discount on Flutter Machine Learning & AI Courses

If you want to build Machine Learning and AI based smart Flutter apps then check our Mobile Machine Learning courses on udemy. Avail 92% off with coupon code “MOBILEMLAI” only for limited time

  1. Flutter & AI: Build Image & Art Generation Flutter App
  2. Flutter & OCR — Build Document Scanner Clone in Flutter
  3. Face Recognition and Detection in Flutter — The 2024 Guide
  4. FlutterFlow for Beginners: Build “No Code” Apps in 2024
  5. Flutter & Google Gemini — Build Chatbots and Assistants
  6. Flutter & ML : Train Tensorflow Lite models for Flutter Apps
  7. Train Object Detection & Image Classify models for Flutter
  8. Machine Learning use in Flutter — The 2024 Guide
  9. Train Image Classification Models & Build Smart Flutter Apps 2024
  10. Build Gallery App Clone in Flutter With Circle To Search Feature

--

--

Hamza Asif
Hamza Asif

Written by Hamza Asif

Udemy Instructor, Flutter Dev helping people Integrate ML & AI in Mobile Apps . Visit my courses https://www.udemy.com/user/e1c14fb5-1c9b-45ef-a479-bbc543e33254

No responses yet