Image Picker
is a Flutter package that provides an easy way to select images and videos from the user’s gallery or camera. It is a great tool to use in applications that require users to upload or select images, such as social media or e-commerce applications.
The image_picker
package supports both iOS and Android platforms and provides several features that make it easy to use. These features include the ability to select images from the gallery or capture images from the camera, the ability to crop images, and the ability to specify image and video quality.
Installing image_picker
To start using image_picker
, you need to add it as a dependency in your pubspec.yaml
file:
dependencies:
flutter:
sdk: flutter
image_picker: ^0.8.3+1
After adding it, run flutter pub get
to install the package.
Using image_picker
Here’s an example of how to use image_picker
to select an image from the gallery:
import 'package:image_picker/image_picker.dart';
import 'package:flutter/material.dart';
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
File? _image;
final picker = ImagePicker();
Future getImage() async {
final pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
if (pickedFile != null) {
_image = File(pickedFile.path);
} else {
print('No image selected.');
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Image Picker Example'),
),
body: Center(
child: _image == null
? Text('No image selected.')
: Image.file(_image!),
),
floatingActionButton: FloatingActionButton(
onPressed: getImage,
tooltip: 'Pick Image',
child: Icon(Icons.add_a_photo),
),
);
}
}
In this example, we create a stateful widget that displays an image selected from the gallery. We use the ImagePicker
class to select the image and then display it using the Image
widget.
The getImage()
method is triggered when the user taps the floating action button. This method opens the gallery and waits for the user to select an image. If an image is selected, the method updates the state of the widget and displays the selected image.
Selecting images from the camera
Here’s an example of how to use image_picker
to capture an image using the camera:
Future getImage() async {
final pickedFile = await picker.getImage(source: ImageSource.camera);
setState(() {
if (pickedFile != null) {
_image = File(pickedFile.path);
} else {
print('No image selected.');
}
});
}
In this example, we use the getImage()
method to capture an image using the device’s camera. We pass the ImageSource.camera
constant as an argument to the getImage()
method to specify that we want to capture an image using the camera instead of selecting an image from the gallery.