Getting a "File$" instead of a File in flutter - flutter

I am allowing users to grab a profile pic and upload that picture as file to my server, but I'm getting this error when inputting the image via ImagePickerWeb:
<error>:<getObject: Unexpected error from chrome devtools:>
I don't know if it's my browser or me, but this is what I'm trying:
Future<void> getMultipleImageInfos() async {
var imageFile =
await ImagePickerWeb.getImage(outputType: ImageType.file);
print(imageFile);
if (imageFile != null) {
setState(() {
currentSelfie = imageFile;
_accDetails['customer_selfie'] = currentSelfie;
});
}
}
Then displaying that photo here:
Image.file(
currentSelfie,
height: screenAwareSize(100, context),
width: screenAwareSize(100, context),
fit: BoxFit.fill,
)

Related

File Picker png format images is giving issues

I was using ImagePicker in my application to select and upload images, but it recently started giving me errors, and constantly glitches when selecting png format images.
For this reason I switched to File picker. But it only works somewhat, and my application still gets stuck. I can only see its display, the image unfortunately does not get stored in the backend (jpg and jpeg images work fine).
Here is the image picker code (if there is a workaround uploading png images using this package, it would be much appreciated):
final ImagePicker _picker = ImagePicker();
Future imageSelectorGallery() async {
var image = (await _picker.pickImage(
source: ImageSource.gallery,
));
if (image != null) {
Uint8List imageBytes = await image
.readAsBytes(); // A fixed-length list of 8-bit unsigned integers which is the file read as bytes
String baseimage = base64Encode(imageBytes);
if (mounted) setState(() {});
post = baseimage;
Navigator.push(context,MaterialPageRoute(builder: (context) => CreatePosts(post,user,caption,upvotes)));
}
}
Here is the file picker code which I have implemented, any help figuring out the error here would also be appreciated:
Future imageSelectorGallery() async {
FilePickerResult? image = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'],
);
if (image != null) {
Uint8List? imageBytes = image.files.first.bytes;
String baseimage = base64Encode(imageBytes!);
if (mounted) setState(() {});
post = baseimage;
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CreatePosts(post, user, caption, upvotes)));
} else {
print("File picker error");
}
}
The image is displayed using:
child: Container(
height:
MediaQuery.of(context).size.height / 4.3,
width: MediaQuery.of(context).size.width / 3.4,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
image: DecorationImage(
fit: BoxFit.cover,
image: Image.memory(
_bytesImage,
gaplessPlayback: true,
).image,
))),
),

Cannot upload image chosen from gallery on Flutter: "Cannot extract a file path from a blob"

I have this image uploading API:
http://localhost:1234/simpleApi/image/upload
Given an image file test_image.jpg, here's how you upload it via HTTPie:
http POST http://localhost:1234/simpleApi/image/upload file#test_image.jpg
If uploaded succesfully, an UUID will be returned.
Now I'm trying to do the same thing on Flutter, first pick the image from gallery, then call the image upload API:
pickImage() async {
XFile? result;
try {
result = await ImagePicker().pickImage(
source: ImageSource.gallery,
imageQuality: 70,
maxWidth: 1024,
);
} on PlatformException {
Get.snackbar('', 'Cannot access gallery...');
}
if (result != null) {
setState(() {
_imgPath = result!.path;
});
}
}
uploadImage(String pathToFile) async {
var IMAGE_UPLOAD_URL = 'http://localhost:1234/simpleApi/image/upload'
var postUri = Uri.parse("IMAGE_UPLOAD_URL");
var request = new http.MultipartRequest("POST", postUri);
request.files.add(new http.MultipartFile.fromBytes('file', await File.fromUri(Uri.parse(pathToFile)).readAsBytes(),
contentType: new MediaType('image', 'jpeg')));
request.send().then((response) {
if (response.statusCode == 200) print("Upload OK");
else ("Upload failed.");
});
}
After calling pickImage, it returns a value like this:
blob:http://localhost:64692/a4b07098-0e83-46e2-8bdd-7a0a93aedec3
Passing that value to uploadImage gives this error:
Error: Unsupported operation: Cannot extract a file path from a blob
URI
How to fix this? I tested this on Flutter 2.2.3
You have everything right, the only thing you have to take note of is which platform are you reading this image from, when you check the example on Pub.dev you will notice that you have to check using kIsweb, that way the system will read your blob as a network image.
Obx(() => controller.filepath.value == ""
? Text(
"Select image",
style: TextStyle(fontSize: 20),
)
: Semantics(
label:
'image_picker_example_picked_image',
**child: kIsWeb
? Image.network(
controller.filepath.value)
: Image.file(
File(controller.filepath.value)),
)**
instead of URI you can use this
http.MultipartFile.fromBytes(
'image',
uint8list,
filename: imageName,
);

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

Flutter error while showing profile picture google play games

Using the play_games extension, I'm having trouble returning the user's profile image.
Use the method below to login and set the state with the return of the user's data.
Image provider: NetworkImage ("content: //com.google.android.gms.games.background/images/f56551ac/42", scale: 1.0)
// Google Play Games stance
final GameServices gameservices = GameServices();
Account profile;
ui.Image profileimage;
void _login() async {
final res = await gameservices.login();
final resimage = await res.hiResImage;
setState(() {
profile = res;
profileimage = resimage;
});
print(profileimage);
}
In the widget I'm in the form of NetworkImage, but it's still not rendering on the screen.
this error: The argument type 'Image' can't be assigned to the parameter type 'String'.
Container(
width: 128,
height: 128,
padding: EdgeInsets.all(8),
child: CircleAvatar(
backgroundImage: NetworkImage(this.profileimage != null ? this.profileimage : 'https://api.adorable.io/avatars/128/')
),
decoration: BoxDecoration(
color: Colors.white,
shape: BoxShape.circle
),
),
[ RESOLVED!!! ]
Change my code and play_games returns type vars.
Lets go:
Future<Uint8List> get hiResImage async =>
await _fetchToMemory(await _channel.invokeMethod('getHiResImage'));
Future<Uint8List> get iconImage async =>
await _fetchToMemory(await _channel.invokeMethod('getIconImage'));
}
Future<Uint8List> _fetchToMemory(Map<dynamic, dynamic> result) {
Uint8List bytes = result['bytes'];
if (bytes == null) {
print('was null, mate');
return Future.value(null);
}
// Completer<Image> completer = new Completer();
// decodeImageFromList(bytes, (image) => completer.complete(image));
return Future.value(bytes);
}
And my code, only this change:
Uint8List profileimage;
Flutter is yelling at you because you gave it a URL with protocol content://, when it expects http:// or https:// for a NetworkImage widget. See documentation at: https://flutter.dev/docs/cookbook/images/network-image
This happen because google provide encoded image. In android we can use ImageManager for that as google suggest.
In flutter there are mechanism for getting Future<Image> from hiresImageUri. Check here.
Use Something like below,
profile.hiResImage.then((Image result){
//here you can get image in result
});

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

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