Flutter: why image_picker doesn't open the photos from my gallery? - flutter

I'm new in Flutter and can't get image_picker to open a picture from gallery.
It opens Gallery, but when I tap on a picture, just close gallery
My code is like this.. what i'm missing?
File _imagenTemporal;
var imagen;
Future getImagen(String opcion) async {
if (opcion == "camara") {
imagen = await ImagePicker.pickImage(source: ImageSource.camera);
} else if (opcion == "galeria") {
imagen = await ImagePicker.pickImage(source: ImageSource.gallery);
}
setState(() {
_imagenTemporal = imagen;
}
);
}

ImagePicker is just a FileChooser function that returns a Future<File> widget when the user selects a File from the gallery or takes a picture. You should use the returned file to construct an Image.file widget:
Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: showSelectedImage();
),
Future<Image> showSelectedImage() async {
_imagenTemporal = await ImagePicker.pickImage(source: ImageSource.gallery);
return Image.file(_imageTemporal);
}

Related

Flutter Firebase: storage on web with imagePicker

I have an implementation of imagePicker working with the mobile portion of my app, but i am currently trying to make it work on web too. Im getting an image with the following code:
ImagePicker _picker = ImagePicker();
final XFile? _image = await _picker.pickImage(
source: ImageSource.gallery,
imageQuality: 50,
);
if (_image == null) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('No image was selected.')));
}
if (_image != null) {
var f = await _image.readAsBytes();
StorageRepository()
.updateImage(user, _image, index);
}
Which leads to my confusion. My current storage method looks like this:
Future<void> uploadImageWeb(User user, XFile image, int? index) async {
try {
await storage
.ref('${user.id}/${image.name}')
.putFile(
File(image.path),
)
.then(
(p0) => FirestoreRepository().updateUserPictures(
user,
image.name,
index,
),
);
} catch (err) {
print(err);
}
}
Which obviously i cant use xfile, i have to use the Uint8List. But how do i read any data from that in a meaningful way to upload it to the storage bucket?
Thanks!

Flutter rebuilds widget without waiting for code execution

I have a function to upload image to the server. However the widgets starts rebuilding while the image is being uploaded and does not execute code after image is uploaded.
InkWell(
child: Icon(
Icons.camera,
size: 50,
color: Colors.red[400],
),
onTap: () {
_imageFile =
_picker.getImage(source: ImageSource.camera);
_imageFile.then((file) async {
if (file != null) {
fileName = file.path.toString();
var res = await Auth.uploadImage(file);
print("Response for image upload is : ");
print(res);
await setUserData();
}
});
},
)
This is the output on the console from print statements
I/flutter (10171): Calling build Method
I/Timeline(10171): Timeline: Activity_launch_request time:68831133
I/flutter (10171): Uploading image to server
I/flutter (10171): Calling build Method
I/flutter (10171): Image uploaded successfully
As can be seen above no other code is executed and the widget has rebuilt itself. What am I possibly doing wrong?
_imageFile = _picker.getImage(source: ImageSource.camera);
its not right, getImage is an Asynchronous function so you need to wait for it to finish.
do this - _imageFile = await _picker.getImage(source: ImageSource.camera);
If you want to use then do it like this,
_picker.getImage(source: ImageSource.camera).then((image)...your code...)
That's because when you're using _imageFile = _picker.getImage(source: ImageSource.camera); the _imageFile result will come in the future and your next code is executed.
You can fixed the problem either using await:
onTap: () async {
_imageFile =
await _picker.getImage(source: ImageSource.camera);
if (_imageFile != null) {
fileName = file.path.toString();
var res = await Auth.uploadImage(file);
print("Response for image upload is : ");
print(res);
await setUserData();
}
},
Or keep using then with a slight change:
onTap: () {
_picker.getImage(source: ImageSource.camera)
.then((file) async {
if (file != null) {
fileName = file.path.toString();
var res = await Auth.uploadImage(file);
print("Response for image upload is : ");
print(res);
await setUserData();
}
});
},
See explanation about await & then: Async/Await/then in Dart/Flutter

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),

How to use preference for showing profile picture in my application in flutter

I want to display a profile picture of the user when they log in. I am using the image URL stored in firestore database.
I want to keep the image in the app until logout. Every time I start the app, Image is called from that URL but I want to store it. I am new to flutter and have no clue to achieve this task.
Future<void> _getImage(ImageSource source) async {
var image = await ImagePicker.pickImage(source: source);
if (image != null) {
setState(() {
_cropImage(image);
});
}
Navigator.pop(context);
}
// Crop fetched image
_cropImage(File image) async {
File cropped = await ImageCropper.cropImage(
sourcePath: image.path,
aspectRatio: CropAspectRatio(ratioY: 1.0, ratioX: 1.0));
if (cropped != null) {
setState(() {
_imageFile = cropped;
uploadFile();
});
}
}
// Upload image file to firestrore Storage and get image URL
Future uploadFile() async {
StorageReference storageReference = FirebaseStorage.instance
.ref()
.child('${Path.basename(_imageFile.path)}}');
StorageUploadTask uploadTask = storageReference.putFile(_imageFile);
var downUrl = await (await uploadTask.onComplete).ref.getDownloadURL();
var url = downUrl.toString();
await uploadTask.onComplete;
setState(() {
imageUrl = url.toString();
});
// Show message on successful image upload
AppUtils.showToast('Picture Uploaded', green, white);
// Updating database with Image URL
Firestore.instance
.collection('account')
.document(widget.user)
.updateData({"url": imageUrl});
}
// Display Image
ClipRRect(
borderRadius: BorderRadius.circular(200.0),
clipBehavior: Clip.hardEdge,
child: Container(
height: 200,
width: 200,
child: widget.photoUrl == null
? Image(
image: NetworkImage(
'https://cdn1.iconfinder.com/data/icons/technology-devices-2/100/Profile-512.png'),
fit: BoxFit.fill,
)
: Image(
image: NetworkImage(widget.photoUrl),
fit: BoxFit.fill,
))),
What you need is a proper State Management throughout your app.
You can check the Provider Package to get started.
You can find more information about State Management here and here