As a developer working on a Flutter app, you'll likely encounter the need to allow users to pick and display images within your application. Whether it's for a profile picture, uploading images to a gallery, or any other image-related functionality, Flutter provides a straightforward and efficient way to accomplish this task. In this blog post, we will walk you through the process of picking and displaying images in a Flutter app with practical examples.
Prerequisites
Before we begin, ensure you have Flutter installed and set up on your development environment. If you haven't already, head over to the official Flutter website and follow the installation instructions for your platform.
1. Add Dependencies
To enable image picking functionality, we'll need to add the necessary dependencies in our pubspec.yaml
file.
dependencies: flutter: sdk: flutter image_picker: ^0.8.4+3 path_provider: ^2.0.7 path: ^1.8.0
The image_picker
package allows us to access the device's image gallery and camera, while path_provider
and path
packages are used to handle file operations.
After adding the dependencies, run flutter pub get
to install them.
2. Implementing Image Picking
2.1. Image Picker Configuration
2.1.1. Android Configuration
For Android, no additional configuration is required as the image_picker
package utilizes the built-in permissions for accessing the camera and gallery. However, if you plan to use the camera, ensure that you have the necessary camera-related permissions in your AndroidManifest.xml
file:
<uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
2.1.2. iOS Configuration
For iOS, you need to add permission descriptions to your Info.plist
file to request access to the camera and photo library. Open the Info.plist
file (located under the ios/Runner
directory) and add the following lines:
<key>NSCameraUsageDescription</key> <string>Your app needs access to the camera to pick images.</string> <key>NSPhotoLibraryUsageDescription</key> <string>Your app needs access to the photo library to pick images.</string>
These descriptions will be shown to the users when they are prompted to grant access to the camera and photo library.
2.2. Image Picker Widget
In your Flutter app, you can have a button or an interface element that triggers the image picking process. Let's create a button that allows the user to pick an image from the gallery.
import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; import 'dart:io'; class ImagePickerButton extends StatefulWidget { @override _ImagePickerButtonState createState() => _ImagePickerButtonState(); } class _ImagePickerButtonState extends State<ImagePickerButton> { File? _image; Future<void> _pickImage(ImageSource source) async { final pickedFile = await ImagePicker().pickImage(source: source); if (pickedFile != null) { setState(() { _image = File(pickedFile.path); }); } } @override Widget build(BuildContext context) { return Column( children: [ _image != null ? Image.file(_image!) : Placeholder( fallbackHeight: 200, fallbackWidth: double.infinity, ), ElevatedButton( onPressed: () { showDialog( context: context, builder: (context) => AlertDialog( title: Text("Choose an Image"), actions: [ TextButton( onPressed: () { Navigator.of(context).pop(); _pickImage(ImageSource.gallery); }, child: Text("Gallery"), ), TextButton( onPressed: () { Navigator.of(context).pop(); _pickImage(ImageSource.camera); }, child: Text("Camera"), ), ], ), ); }, child: Text("Pick Image"), ), ], ); } }
In the code above, we have created a StatefulWidget
called ImagePickerButton
. When the user taps the "Pick Image" button, an AlertDialog
appears with options to pick an image from the gallery or take a photo using the camera. Once the user selects an image, it is displayed in the app.
2.3. Using the ImagePickerButton
To use the ImagePickerButton
widget in your app, simply add it to any part of your app where you want to allow image picking. For example, if you have a settings screen or a profile page, you can use it like this:
class ProfilePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Profile"), ), body: Center( child: ImagePickerButton(), ), ); } }
Now, when you navigate to the ProfilePage
, you will see the "Pick Image" button, and upon selecting an image, it will be displayed on the screen.
GitHub Repository - Find the complete code for each example in this tutorial on GitHub.
Source Code
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( title: 'FlutterforGeeks', debugShowCheckedModeBanner: false, theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.green), useMaterial3: true, ), home: const MyHomePage(title: 'FlutterforGeeks'), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key, required this.title}); final String title; @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Theme.of(context).colorScheme.primary, title: Text( widget.title, style: const TextStyle(color: Colors.white), ), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ SizedBox( width: MediaQuery.of(context).size.width, child: ImagePickerButton()), ], ), ), ); } } class ImagePickerButton extends StatefulWidget { @override _ImagePickerButtonState createState() => _ImagePickerButtonState(); } class _ImagePickerButtonState extends State<ImagePickerButton> { File? _image; Future<void> _pickImage(ImageSource source) async { final pickedFile = await ImagePicker().pickImage(source: source); if (pickedFile != null) { setState(() { _image = File(pickedFile.path); }); } } @override Widget build(BuildContext context) { return Column( children: [ _image != null ? Image.file(_image!) : const Placeholder( fallbackHeight: 200, fallbackWidth: double.infinity, ), ElevatedButton( onPressed: () { showDialog( context: context, builder: (context) => AlertDialog( title: const Text("Choose an Image"), actions: [ TextButton( onPressed: () { Navigator.of(context).pop(); _pickImage(ImageSource.gallery); }, child: const Text("Gallery"), ), TextButton( onPressed: () { Navigator.of(context).pop(); _pickImage(ImageSource.camera); }, child: const Text("Camera"), ), ], ), ); }, child: const Text("Pick Image"), ), ], ); } }
Video Demo
Conclusion
In this blog post, we've learned how to pick and display images in a Flutter app using the image_picker
package. By following the step-by-step guide and implementing the examples, you can easily integrate image picking functionality into your own Flutter applications.
Allowing users to pick images adds significant versatility to your app, enabling users to personalize their profiles, share images, and enhance the overall user experience. Remember to handle potential errors, such as the user denying access to the gallery or camera, and consider adding loading indicators when the image is being fetched.
Happy coding and enjoy building your feature-rich Flutter app with image picking capabilities!