I have Issues with image picker - flutter

I created a method to pick images in the authcontroller class like so
class AuthController{
pickImage(ImageSource source)async{
final ImagePicker _picker = ImagePicker();
XFile? _file = await _picker.pickImage(source: source);
if(_file != null){
await _file.readAsBytes();
}else{
print('no image selected');
}
}
}
In my main code I created two functions to specify from where exactly we should pick the images after creating a global variable called _image
Uint8List? _image;
selectGalleryImage()async{
Uint8List? _im=await _authController.pickImage(ImageSource.gallery);
setState(() {
_image = _im;
});
}
selectCameraImage()async{
Uint8List? _im=await _authController.pickImage(ImageSource.camera);
setState(() {
_image = _im;
});
}
the problem is when i try to call display _image from either my camera or gallery, it does not display. I can pick images from both mediums, it is just that the image does not display even though i pass it through MemoryImage in the CircleAvater Widget
_image != null ? CircleAvatar(
radius: 44,
backgroundImage: MemoryImage(_image!,)
):const CircleAvatar(
radius: 44,
backgroundColor: Colors.black,
backgroundImage: NetworkImage('https://t4.ftcdn.net/jpg/00/64/67/63/360_F_64676383_LdbmhiNM6Ypzb3FM4PPuFP9rHe7ri8Ju.jpg'),
),
I have added everything addable in the androidmanifest in the main folder.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
and i have run flitter clean multiple times but it still give me the same result. help would be very much appreciated

As one comment says, pickImage is not returning anything.
Change it to this,
class AuthController{
Future<Uint8List?> pickImage(ImageSource source)async{
final ImagePicker _picker = ImagePicker();
XFile? _file = await _picker.pickImage(source: source);
if(_file != null){
return await _file.readAsBytes();
}else{
print('no image selected');
return null;
}
}
}

Related

Flutter Newb, anyone tell me whats wrong with this code?

Following a tutorial for adding and saving images and getting errors for the below code, under ImagePicker, ImageSource and SelectedImage.
Future getImage() async {
var image = await ImagePicker.PickImage(source: ImageSource.camera);
setState(() {
selectedimage = image;
});
}
You need to create an instance first, then you will be able to use pickImage method.
Future getImage() async {
XFile? image = await ImagePicker().pickImage(source: ImageSource.camera);
if (image != null) {
setState(() {
selectedimage = image;
});
}
}
Fine more about image_picker
You have to be careful whenever playing with the setState() functions. This combined with how you pick the image and how you store it in the 'var' in your case could cause further trouble. To generally ease things up for further use I recommend creating a utils class, in which you would have an image picker method, just like this one:
import 'package:image_picker/image_picker.dart';
pickImage(ImageSource source) async {
final ImagePicker _imagePicker = ImagePicker();
XFile? _file = await _imagePicker.pickImage(source: source);
if (_file != null) {
return await _file.readAsBytes();
}
print('No Image Selected');
}
Afterwards, if you would like to call that in any other instance you would need something like this, though this is for a url image(I had it in hand), such as:
void selectImage() async {
Uint8List? im = await pickImage(ImageSource.gallery);
final ByteData imageData = await NetworkAssetBundle(Uri.parse(
"url for template image"))
.load("");
final Uint8List bytes = imageData.buffer.asUint8List();
// if null - use the template image
im ??= bytes;
// update state
setState(() {
_image = im!;
});
}
Hope it helped in a way.

Flutter Image_Picker doesn't pick image from gallery and return to app

Here is a what's happening : I'm trying to upload an image from gallery to my app on iOS simulator. Image Picker opens the gallery but can't select an image and return to app. Here's my simple code:
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.');
}
});
}
and my widget:
body: Center(
child: _image != null ? Image.file(_image) : Text('no Image'),
),
Thank you all in advance
For the iOS, as stated in the documentation, you'll need some config in the native side relating to permission:
Add the following keys to your Info.plist file, located in /ios/Runner/Info.plist:
NSPhotoLibraryUsageDescription - describe why your app needs permission for the photo library. This is called Privacy - Photo Library Usage Description in the visual editor.
NSCameraUsageDescription - describe why your app needs access to the camera. This is called Privacy - Camera Usage Description in the visual editor.
NSMicrophoneUsageDescription - describe why your app needs access to the microphone, if you intend to record videos. This is called Privacy - Microphone Usage Description in the visual editor.
Other than that, it should work perfectly fine with your code. The image should be fit within a Flexible like this, or maybe a SizedBox to avoid overflowing:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
void main() {
runApp(MaterialApp(
home: SampleScreen(),
));
}
class SampleScreen extends StatefulWidget {
#override
_SampleScreenState createState() => _SampleScreenState();
}
class _SampleScreenState extends State<SampleScreen> {
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(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
FlatButton(onPressed: () => getImage(), child: Text('Press me')),
Flexible(child: _image != null ? Image.file(_image) : Text('no Image')),
],
),
),
);
}
}
File _image;
String _image1 = "";
Future getImage() async {
final pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
if (pickedFile != null) {
_image1 = pickedFile.path;
_image = File(pickedFile.path);
print(json.encode(_image1));
print("file path...");
} else {
print('No image selected.');
}
});
}
In my case, I update my Image picker library from 0.6.3 to 0.8.4
hope this helps anyone.
You need to add the user permissions(key) and add the purpose(values) of these in info.plist file in iOS module.
Add the following keys to your Info.plist file, located in /ios/Runner/Info.plist:
NSPhotoLibraryUsageDescription - describe why your app needs permission for the photo library. This is called Privacy - Photo Library Usage Description in the visual editor.
NSCameraUsageDescription - describe why your app needs access to the camera. This is called Privacy - Camera Usage Description in the visual editor.
dependencies:
image_picker: ^0.8.4+4
import 'package:image_picker/image_picker.dart';
final picker = ImagePicker();
Future pickImage() async {
setState(() {
picselected1 = false;
});
ImagePicker picker = ImagePicker();
PickedFile pickedFile;
pickedFile = await picker.getImage(
source: ImageSource.gallery,
);
setState(() {
if (pickedFile != null) {
picselected1 = true;
// _images.add(File(pickedFile.path));
_image = File(pickedFile.path); // Use if you only need a single picture
} else {
print('No image selected.');
}
});
}
For everyone still dealing with this problem
Please not this in the image_picker documentary and make sure you tested it on a real device:
Starting with version 0.8.1 the iOS implementation uses PHPicker to
pick (multiple) images on iOS 14 or higher. As a result of
implementing PHPicker it becomes impossible to pick HEIC images on the
iOS simulator in iOS 14+. This is a known issue. Please test this on a
real device, or test with non-HEIC images until Apple solves this
issue

Display Default Image if wasn't picked by Image Picker in Flutter

I have an image picker function, that picks image from gallery and then assigns that to _image variable which is String. It converts it to base64 because that is what was necessary. I want to know how would I go about getting the default image from assets as the _image if no image was picked (picked image is null). Here's the code and things I've tried commented out, it is under else in code:
Future _getImage() async {
PickedFile pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
if (pickedFile != null) {
final file = File(pickedFile.path);
_image = Utility.base64String(file.readAsBytesSync());
} else {
//if image wasn't picked, get the default one from assets
print('No image selected.');
// final file = File(AssetImage('assets/defaultfood.jpg').toString());
// _image = Utility.base64String(file.readAsBytesSync());
//final file = File('assets/defaultfood.jpg');
//_image = Utility.base64String(file.readAsBytesSync());
}
});
}
add image placeholder like this ternary condition
child: pickedFile == null ? Image.asset("assets/images/man_user.png",height: 100, width: 100): Image.file(pickedFile, height: 100, width: 100),

Image picker scanned to null

File _image;
final picker = ImagePicker();
Future getImage() async {
final pickedFile = await picker.getImage(source: ImageSource.camera);
setState(() {
if (pickedFile != null) {
_image = File(pickedFile.path);
} else {
print('No image selected.');
}
});
}
output :
D/MediaScannerConnection(16161): Scanned
/storage/emulated/0/Android/data/com.xxxx.xxxx/files/Pictures/9d9ed6a1-292c-428a-bf24-38ea1a58742c6940060118053310767.jpg
to null
This problem occurred to me too. I have found that somehow the captured image data is lost due to the MainActivity is killed after the image_picker finishes. To solve this, just add retrieve lost data handler. You can find the example code on the documentation here. (Refer section: Handling MainActivity destruction on Android #)

White/blank screen after close camera in Flutter

I have a widget to take pictures on my app working like so:
final File imageFile =
await ImagePicker.pickImage(source: ImageSource.camera).then((test) {
print('TEST $test');
return test;
});
I can open the camera without any error and also take the picture but when I try to go back or accept the picture I've taken the app displays an white screen and the console show no errors at all.
This is failing on a real device (Xiaomi Redmi Note 8t) but it works on Android Emulator.
The only message I can see is Lost connection to device. when I take the camera
Fixed adding a try catch:
Future<Null> _pickImageFromCamera(BuildContext context, int index) async {
File imageFile;
try {
imageFile = await ImagePicker.pickImage(source: ImageSource.camera)
.then((picture) {
return picture; // I found this .then necessary
});
} catch (eror) {
print('error taking picture ${error.toString()}');
}
setState(() => this._imageFile = imageFile);
}
I found the solution for flutter 2
In Android
You need to add this to your 3 manifest (debug, main , profile)
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Then pick the image with a try catch, like this
Future getbehind() async {
try{
final pickedFile = await picker.getImage(source: (ImageSource.camera:ImageSource.gallery),)
.then((value) {
setState(() {
if (value != null) {
behind = File(value.path);
} else {
print('No image selected.');
}
});
});
}catch(e){
}
Run the app in a release mode and its done!