In this post, we will learn how to pick images in a flutter app using a camera and phone storage. This tutorial will guide step by step on how you can capture an image from your phone camera and display it to your app and how you can pick an image from Gallery and then show it to the user.
For getting the result we will use a plugin. I will explain to you about the flutter imagepicker plugin that we will be using for this app.
I am assuming that you have the basic knowledge of flutter like creating the project and you know what is widget.
Let’s start…
Step: 1 – Creating the flutter project
First, you need to create a flutter project for this use this command.
flutter create project_name
Step: 2 – Adding the dependencies
Now go to your pubspec.yaml file and add package image_picker this is the package that flutters provides us for getting access to the gallery and camera for taking images. You can add these lines to pubspec.yaml file
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
image_picker: ^0.8.5+3
Or you can do it by the terminal. Go to your project root and then in the terminal type this command.
flutter pub add image_picker
It will add the image_picker plugin in your pubspec.yaml file now we will have all the properties and methods given by this package.
Step: 3 – Editing the main.dart file.
Now go to your main.dart file and delete everything because we will make this app from scratch. copy and paste this code to your main.dart
import 'package:flutter/material.dart';
import 'package:multiselectdrop/pick_date_and_time.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const PickImageExample(),
);
}
}
Step:4 – Creating the home page
Next step is to create a home page for our app for this create a new file and name it pick_image_Example.dart inside your lib folder.
Make inside this file make a statefulwidget and name it PickImageExample and call this class from main.dart file because we have made it our home page.
The code for the pick_image_example.dart file is as follows
import 'package:flutter/material.dart';
class PickImageExample extends StatefulWidget {
const PickImageExample({Key? key}) : super(key: key);
@override
State<PickImageExample> createState() => _PickImageExampleState();
}
class _PickImageExampleState extends State<PickImageExample> {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color.fromARGB(255, 59, 59, 59),
appBar: AppBar(
title: const Text('Image Picker Example'),
),
body: Center(
child: Column(
children: [
MaterialButton(
color: Colors.blue,
child: const Text("Pick Image from Gallery",
style: TextStyle(color: Colors.white)),
onPressed: () {}),
MaterialButton(
color: Colors.blue,
child: const Text("Pick Image from Camera",
style: TextStyle(color: Colors.white)),
onPressed: () {}),
],
),
),
);
}
}
Now run the app you will see your app like this.
We have used the center widget and inside this, we took a column, and for children this column we took two buttons one for taking images from the gallery and one for picking images from the camera.
We will pick images from these buttons and display on below the buttons.
Step: 5 – Display the image
For displaying an image programmatically create two variables (inside your _pickImageExampleState) one is bool type and the other is File type don’t forget to import dart.io.
bool isImageSelected = false;
File? imageFile;
We will use the isImageSelcted variable for checking if the user selects any or not if selected we will show it otherwise we won’t show it. See the full code for this functionality.
Step: 6 – Pick an image from the gallery
For picking an image from the gallery make a function _pickImageFromGallery inside your class _pickImageExampleState and make it async. And call this method from the first buttons onPressed function.
_pickImagefromGallery() async {
try {
final pickedImage =
await ImagePicker().pickImage(source: ImageSource.gallery);
if (pickedImage != null) {
setState(() {
imageFile = File(pickedImage.path);
isImageSelected = true;
});
} else {
print('User didnt pick any image.');
}
} catch (e) {
print(e.toString());
}
}
We use the try-catch block as you can see we took the pickedImage variable for picking an image from the gallery it waits for the user to pick an image from the gallery.
The ImagePicker() class does work for us it has the pickImage method which takes the source as a parameter and for the source, we have passed ImageSource.gallery. As soon as the user picks an image we use setState method to update the UI.
Remember we took a bool type variable isImageSelected and File type variable imageFile now we use these for updating the UI and displaying images inside setState we give a value of true to isImageSelected variable and for the imageFile we give the image path inside a File function.
The pickImage X-File type object so for displaying the image we have to have a File type object because we used FileImage() widget to display the image. Once the user selects the image it your app will show an image like the below image.
Step: 7 – Pick an image from the camera
We have seen how to display images from the gallery now we will see how to display images from the camera for this first we have to capture an image. for capturing the image we don’t have to use any other package this image picker package does this task for us.
Make another method as we made for picking the image from the gallery the only difference will be the image source just replace imageSource with imageSource.gallery to imageSource.camera
And you are good to go it automatically opens the camera and lets the user capture image and once the user captures the image it will display on the screen. For code, this method is as below.
_pickImagefromCamera() async {
try {
final pickedImage =
await ImagePicker().pickImage(source: ImageSource.camera);
if (pickedImage != null) {
setState(() {
imageFile = File(pickedImage.path);
isImageSelected = true;
});
} else {
print('User didnt pick any image.');
}
} catch (e) {
print(e.toString());
}
}
You have to call this method from the second button’s onPressed function.
Step: 8 – Full code.
The full code for the app is as follows just copy and paste it to the file
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
class PickImageExample extends StatefulWidget {
const PickImageExample({Key? key}) : super(key: key);
@override
State<PickImageExample> createState() => _PickImageExampleState();
}
class _PickImageExampleState extends State<PickImageExample> {
bool isImageSelected = false;
File? imageFile;
_pickImagefromGallery() async {
try {
final pickedImage =
await ImagePicker().pickImage(source: ImageSource.gallery);
if (pickedImage != null) {
setState(() {
imageFile = File(pickedImage.path);
isImageSelected = true;
});
} else {
print('User didnt pick any image.');
}
} catch (e) {
print(e.toString());
}
}
_pickImagefromCamera() async {
try {
final pickedImage =
await ImagePicker().pickImage(source: ImageSource.camera);
if (pickedImage != null) {
setState(() {
imageFile = File(pickedImage.path);
isImageSelected = true;
});
} else {
print('User didnt pick any image.');
}
} catch (e) {
print(e.toString());
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color.fromARGB(255, 59, 59, 59),
appBar: AppBar(
title: const Text('Image Picker Example'),
),
body: Center(
child: Column(
children: [
MaterialButton(
color: Colors.blue,
child: const Text("Pick Image from Gallery",
style: TextStyle(color: Colors.white)),
onPressed: () async {
await _pickImagefromGallery();
}),
MaterialButton(
color: Colors.blue,
child: const Text("Pick Image from Camera",
style: TextStyle(color: Colors.white)),
onPressed: () async {
await _pickImagefromCamera();
}),
isImageSelected
? Expanded(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Image(
image: FileImage(imageFile!),
),
),
)
: Container(),
],
),
),
);
}
}
Package Link – (https://pub.dev/packages/image_picker).
For more Flutter tutorials, Tips, Tricks, Free code, Questions, and Error Solving.
Remember FlutterDecode.com