Flutter Image Picker

Flutter Image Picker:

In this tutorial, we are going to learn Flutter Image Picking form mobile gallery OR taking a new picture with your mobile camera for both Android and IOs.

Why Flutter Image picker?

Some times we need to pick an image or photo from mobile to upload it into an application form whenever required if we are applying for any job online this is one example but there are so many advantages of Flutter Image Picker. If you want to share the photos are images that you attract more with your friends you need to pick the image from your mobile to share and nowadays selfie is trending taking a selfie and sharing it with your friends for this purpose you need a flutter image picker.

Creating Image Picker Functionality In Flutter:

Follow the below steps to create image picker functionality in Flutter.

Add the dependency Package:

To implement flutter image picker functionality, we have to add the dependency package to pubspec.yaml file. use the below code to add dependency package. After adding the dependency package run the get package method to import all the required files to the app.

 

dependencies:
image_picker: ^0.6.0+3

Install the package:

You can install the package from the command line using the below code with Flutter as shown.

$ flutter packages get

Importing the Package:

After, Adding the dependency package to the pubspec.yaml file, you can now import the package into the dart code by using the below code. without adding the dependency package to the pubspec.yaml file if you import it will show package not found an error.

import ‘package:image_picker/image_picker.dart’;

IOS Image Picker setup in Flutter:

Add the below  key values to your Info.plist file, located in /ios/Runner/Info.plist:

  • NSPhotoLibraryUsageDescription –  this describes why your app needs permission for the photo library. This is because of a Privacy – Photo Library Usage Description in the visual editor.
  • NSCameraUsageDescription – this value describes why your app needs camera access. This is called Privacy because– Camera Usage Description in the visual editor.
  • NSMicrophoneUsageDescription – we need to use this value to describe why your app needs access to the microphone if you want to record videos. This is called Privacy – Microphone Usage Description in the visual editor.

 

Android Image Picker setup in Flutter:

We no need any setup for Android in Flutter.

 

Example code to pick Image from the Gallery and Camera.

import 'package:image_picker/image_picker.dart';

class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State {
File _image;

Future getImage() async {
var image = await ImagePicker.pickImage(source: ImageSource.camera);

setState(() {
_image = image;
});
}

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

Handling the selected Image lost in Flutter for Android App:

The Android operating system sometimes very rarely kills the MainActivity after the image picking finishes. This will cause lost data selected from the image picker. To avoid selected image or selected data lost in Android You can use retrieveLostData to retrieve the lost data in this situation.

For example: use the below code to fetch the selected data lost data 

Future retrieveLostData() async {
final RetrieveLostDataResponse response =
await ImagePicker.retrieveLostData();
if (response == null) {
return;
}
if (response.file != null) {
setState(() {
if (response.type == RetrieveType.video) {
_handleVideo(response.file);
} else {
_handleImage(response.file);
}
});
} else {
_handleError(response.exception);
}
}

Complete Example code for Flutter Image Picker:

import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:video_player/video_player.dart';

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

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Image Picker Demo',
home: MyHomePage(title: 'Image Picker Example'),
);
}
}

class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);

final String title;

@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State {
File _imageFile;
dynamic _pickImageError;
bool isVideo = false;
VideoPlayerController _controller;
String _retrieveDataError;

void _onImageButtonPressed(ImageSource source) async {
if (_controller != null) {
_controller.setVolume(0.0);
_controller.removeListener(_onVideoControllerUpdate);
}
if (isVideo) {
ImagePicker.pickVideo(source: source).then((File file) {
if (file != null && mounted) {
setState(() {
_controller = VideoPlayerController.file(file)
..addListener(_onVideoControllerUpdate)
..setVolume(1.0)
..initialize()
..setLooping(true)
..play();
});
}
});
} else {
try {
_imageFile = await ImagePicker.pickImage(source: source);
} catch (e) {
_pickImageError = e;
}
setState(() {});
}
}

void _onVideoControllerUpdate() {
setState(() {});
}

@override
void deactivate() {
if (_controller != null) {
_controller.setVolume(0.0);
_controller.removeListener(_onVideoControllerUpdate);
}
super.deactivate();
}

@override
void dispose() {
if (_controller != null) {
_controller.dispose();
}
super.dispose();
}

Widget _previewVideo(VideoPlayerController controller) {
final Text retrieveError = _getRetrieveErrorWidget();
if (retrieveError != null) {
return retrieveError;
}
if (controller == null) {
return const Text(
'You have not yet picked a video',
textAlign: TextAlign.center,
);
} else if (controller.value.initialized) {
return Padding(
padding: const EdgeInsets.all(10.0),
child: AspectRatioVideo(controller),
);
} else {
return const Text(
'Error Loading Video',
textAlign: TextAlign.center,
);
}
}

Widget _previewImage() {
final Text retrieveError = _getRetrieveErrorWidget();
if (retrieveError != null) {
return retrieveError;
}
if (_imageFile != null) {
return Image.file(_imageFile);
} else if (_pickImageError != null) {
return Text(
'Pick image error: $_pickImageError',
textAlign: TextAlign.center,
);
} else {
return const Text(
'You have not yet picked an image.',
textAlign: TextAlign.center,
);
}
}

Future retrieveLostData() async {
final LostDataResponse response = await ImagePicker.retrieveLostData();
if (response.isEmpty) {
return;
}
if (response.file != null) {
setState(() {
if (response.type == RetrieveType.video) {
isVideo = true;
_controller = VideoPlayerController.file(response.file)
..addListener(_onVideoControllerUpdate)
..setVolume(1.0)
..initialize()
..setLooping(true)
..play();
} else {
isVideo = false;
_imageFile = response.file;
}
});
} else {
_retrieveDataError = response.exception.code;
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Platform.isAndroid
? FutureBuilder(
future: retrieveLostData(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
return const Text(
'You have not yet picked an image.',
textAlign: TextAlign.center,
);
case ConnectionState.done:
return isVideo
? _previewVideo(_controller)
: _previewImage();
default:
if (snapshot.hasError) {
return Text(
'Pick image/video error: ${snapshot.error}}',
textAlign: TextAlign.center,
);
} else {
const Text(
'You have not yet picked an image.',
textAlign: TextAlign.center,
);
}
}
},
)
: (isVideo ? _previewVideo(_controller) : _previewImage()),
),
floatingActionButton: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
FloatingActionButton(
onPressed: () {
isVideo = false;
_onImageButtonPressed(ImageSource.gallery);
},
heroTag: 'image0',
tooltip: 'Pick Image from gallery',
child: const Icon(Icons.photo_library),
),
Padding(
padding: const EdgeInsets.only(top: 16.0),
child: FloatingActionButton(
onPressed: () {
isVideo = false;
_onImageButtonPressed(ImageSource.camera);
},
heroTag: 'image1',
tooltip: 'Take a Photo',
child: const Icon(Icons.camera_alt),
),
),
Padding(
padding: const EdgeInsets.only(top: 16.0),
child: FloatingActionButton(
backgroundColor: Colors.red,
onPressed: () {
isVideo = true;
_onImageButtonPressed(ImageSource.gallery);
},
heroTag: 'video0',
tooltip: 'Pick Video from gallery',
child: const Icon(Icons.video_library),
),
),
Padding(
padding: const EdgeInsets.only(top: 16.0),
child: FloatingActionButton(
backgroundColor: Colors.red,
onPressed: () {
isVideo = true;
_onImageButtonPressed(ImageSource.camera);
},
heroTag: 'video1',
tooltip: 'Take a Video',
child: const Icon(Icons.videocam),
),
),
],
),
);
}

Text _getRetrieveErrorWidget() {
if (_retrieveDataError != null) {
final Text result = Text(_retrieveDataError);
_retrieveDataError = null;
return result;
}
return null;
}
}

class AspectRatioVideo extends StatefulWidget {
AspectRatioVideo(this.controller);

final VideoPlayerController controller;

@override
AspectRatioVideoState createState() => AspectRatioVideoState();
}

class AspectRatioVideoState extends State {
VideoPlayerController get controller => widget.controller;
bool initialized = false;

void _onVideoControllerUpdate() {
if (!mounted) {
return;
}
if (initialized != controller.value.initialized) {
initialized = controller.value.initialized;
setState(() {});
}
}

@override
void initState() {
super.initState();
controller.addListener(_onVideoControllerUpdate);
}

@override
Widget build(BuildContext context) {
if (initialized) {
return Center(
child: AspectRatio(
aspectRatio: controller.value?.aspectRatio,
child: VideoPlayer(controller),
),
);
} else {
return Container();
}
}
}

Congratulations You Have Learned  Picking Image From Gallery OR From Camera for Android and IOS Apps….!!!

If It Is Helpful Share It With Your Friends….!!!

Leave a Reply

Categories