Selecting image from Gallery or Camera in Flutter - flutter

I am trying to give users a method to add a photo from their gallery or their camera but, flutter keeps crashing after the button is pressed.
I've implemented the image picker dependency as well as Dart:io, migrated to Android X but, still no luck. Here is some of my code:
class _PreferencesState extends State<_Preferences>
with TickerProviderStateMixin {
File _image;
getImage(bool isCamera) async {
File image;
if (isCamera) {
image = await ImagePicker.pickImage(source: ImageSource.camera);
} else {
image = await ImagePicker.pickImage(source: ImageSource.gallery);
}
setState(() {
_image = image;
});
}
Then called here:
FlatButton(
textColor: Theme.of(context).primaryColor,
child: Text('Use Camera'),
onPressed: () {
getImage(true);
},
),
_image == null
? Container()
: Image.file(
_image,
height: 300,
width: 300,
),
Every time I call the method I get this error:
Exception has occurred.
PlatformException (PlatformException(error, Attempt to invoke virtual method 'android.content.res.XmlResourceParser android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference, null))
I thought I changed the image type from null so it wouldn't be called but, I'm not sure what else to do here.

The crash could be due to camera permission. Image picker plugin has removed the camera permission condition. When we access camera, app asks us for permission, but this condition in not supported anymore. We need to ask the permission manually using permission_handler plugin. Read more details about this change here and see this link on how to add runtime permission using permission_handler. Hope this resolves your issue.

This might not be the best way to do it but if you want to solve the solution more fast and easy you can just clean all your packages and delete the project then build it again. Use the commands below for the whole process:
Navigate to the folder with the pubspec.yaml file and perform the functions below on your terminal:
[user#machine~]$ flutter clean
[user#machine~]$ adb uninstall com.example.myfirst
[user#machine~]$ flutter build apk
[user#machine~]$ flutter pub get
[user#machine~]$ flutter doctor -v
[user#machine~]$ flutter pub upgrade --major-versions
[user#machine~]$ flutter run
When the the android sdk phone starts ensure you allow the app to access your phone files when you click the button to upload images/files from the gallery
N/B: This worked for my app may it might work on yours or not.

Related

How to launch system File Manager from Flutter app?

From my flutter I want to launch the default File Manager. I don't want to select file from it for my app. I just want to launch it (preferably showing the directory that I want it to show) so that the user can pick a file from that directory and do whatever they want with it.
Can anyone please tell me how to do it? I see a lot of code and examples for picking a file but that's not what I need. Just want to launch whatever is a default file manager.
Please do not suggest FilePicker. That is not what I am looking for. I do not want to "pick" a file. I know how to pick a file. I just want the default file manager app to be launched. I don't want the control to be returned back to the app irrespective of whether the user selects a file or not.
This was causing me grief too. Here's my solution.
Using 'external_app_launcher' you are able to launch apps based on their URL scheme, so we have...
import 'package:external_app_launcher/external_app_launcher.dart';
okButton = TextButton(
child: const Text("Open Files"),
onPressed: () async {
await LaunchApp.openApp(iosUrlScheme: 'shareddocuments://', openStore: false);
},
);
This will launch the app, I'm still working my solution as I want to open my App's folder so will update as I get more.
You can use the file_picker package.
Usage
FilePickerResult? result = await FilePicker.platform.pickFiles();
if (result != null) {
File file = File(result.files.single.path);
} else {
// User canceled the picker
}
Edit: Now I understand what you want. Check https://pub.dev/packages/external_app_launcher

Flutter - How implement a file, image and camera picker for local storage

Hi, I would like to implement something like this in flutter. A button from which I can upload local photos from the camera or from images and files in the device to the app. Once I have taken the file I want it to appear near the button with the preview of the file as shown in the example and with the possibility of removing them. What's the best way to do this? Is there a package that does these things?
Thanks in advance!
Yes, there is! The package is image_picker.
To install it, add it as a dependency to your pubspec.yaml or run flutter pub add image_picker.
dependencies:
image_picker: ^0.8.5
Here's an example of how I've used it in my recent app:
final XFile? pickedFile = await ImagePicker().pickImage(source:
ImageSource.gallery); //This opens the gallery and lets the user pick the image
if (pickedFile == null) return; //Checks if the user did actually pick something
final File image = (File(pickedFile.path)); //This is the image the user picked
Once you've got the image, you could use a container to show it.
Container(
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.fill,
image: Image.file(image),
),
),
)

Flutter url_launcher not working MissingPluginException

i want to launch google map when tap on button, nothing complicated. i found easy code also from google search. Pasting the code below for reference. i dont know it is the proper way to do.
class MapUtils {
MapUtils._();
static Future<void> openMap(double latitude, double longitude) async {
String googleUrl =
'https://www.google.com/maps/search/?api=1&query=$latitude,$longitude';
if (await canLaunch(googleUrl)) {
await launch(googleUrl);
} else {
throw 'Could not open the map.';
}
}
}
pubspec.yaml added -> url_launcher: ^6.0.17
i called this -> MapUtils.openMap(-33.2445107, 9.1530103)
Whenever i tap on the button return error as "Unhandled Exception: MissingPluginException(No implementation found for method launch on channel plugins.flutter.io/url_launcher)"
i tried to find solution, what i tried is
Flutter clean, flutter pub get.
Close everything reopen
uninstall app from emulator device.
close emulator and restart.
total computer restart.
it is nothing related url_launcher still i add the google map api to androidmanifest and appdelegate. Enables Api.
Lot of popel are asking about the same error. May be i am missing something todo.

image_picker: ^0.7.2+1 makes the app crash

i am using image_picker: ^0.7.2+1 here in my app
i am using this code for opening the camera
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.');
}
});
}
also Added these Permissions in android/app/src/main/AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.INTERNET"
after using above package when my camera is opening immediately the app crashes and in terminal there is no error message it just says device disconnected. (by app crash i mean app restarts (from splash screen )automatically and captured image is also lost)
this above app crashing issue comes only in android 10 or above android version also in android 10 or above (android 11) also this packages does not asks for the permission of camera in android 10 or 11 which i guess can be the actual problem behind this issue
while i use android 8 or device with android version less then android 10 the image_picker: ^0.7.2+1 here works totally fine with same above given code (no changes are made in code just changed the device from android 11 to android 8) the app asks for permission as expected and then camera opens and successfully pic is captured and hence everything works fine nut same thing fails in android 10 or android 11
note : i also tried using permission_handler plugin with image_picker but it also didn't worked for me
can anyone please help me to fix this issue
also if some one know any substitute code or package for image_picker can please tell me.. i just want to take pic from from camera in flutter
I too went through all of this, setting up permission handling, doing the cache fix, and a few other bits I found online, and after a week could not solve it. Image_picker still crashed my app as soon as I took the shot. My solution in the end was to use camera_camera 2.0.1. It is a terrible library name, and it doesn't include compression, but the camera interface is nicer, and it works perfectly out of the box.
import 'package:camera_camera/camera_camera.dart';
onPressed: (){
Navigator.push( context, MaterialPageRoute(
builder: (_) => CameraCamera(
onFile: (file) {
// Do what you like with File file
// I convert to base64 ready to upload
Navigator.pop(context);
},
)))
},
Add android:requestLegacyExternalStorage="true" as an attribute to the <application> tag in AndroidManifest.xml. The attribute is false by default on apps targeting Android Q.
///// SOLVED /////
All you have to do to fix this is add these 6 lines to ios/Runner/Info.plist
<key>NSPhotoLibraryUsageDescription</key>
<string>Allow access to photo library</string>
<key>NSCameraUsageDescription</key>
<string>Allow access to camera to capture photos</string>
<key>NSMicrophoneUsageDescription</key>
<string>Allow access to microphone</string>
I had the same problem on several devices.
And since I used android:launchMode="singleTask" in AndroidManifest.xml everything works fine for me..
After stuck of 2 weeks finding solutions all round, I found my solution to give profile access to my users.
The solution is I used two alternative packages that work well.
For Getting Image Type
file_picker 5.2.2
For Getting Camera Image
camera 0.10.0+4
Now,it is working very well.
Also,we need to give kinda to Flutter as it is trying its best though having platform issue in some cases.

Bug with image picker with flutter on ImageSource.Gallery

Info:
Package: image_picker plugin for flutter, version 0.6.3+1
Android build only, no IOS
Problem:
This is my method to pick an image:
Future<void> pickImage(ImageSource source) async {
File selected = await ImagePicker.pickImage(source: source);
print(selected?.path);
imageFilePath = selected?.path ?? imageFilePath;
}
=> When using ImageSource.gallery, when choosing a picture which is not in cache, 'selected.path' prints null. When selecting a picture which is in cache, it does retrieve it, 'selected.path' prints:
/data/user/0/be.etnic.parrainage_mcf/cache/image_picker2517179621202627006.jpg
Anyone knows what causes this problem and how I can solve it?
Sidenotes:
I can also pick an image by making a picture directly with ImageSource.camera, this doesn't give me any problems.
I'm not 100% sure that the selected pictures that return null
are not in cache, but the pictures that do return correctly from
choosing from the ImageSource.gallery all come from that
cache-folder
I don't have any permissions set in my AndroidManifest.xml
(other than Internet permission)
Based on this link https://github.com/flutter/flutter/issues/41459#issuecomment-563986851, following should solve the problem:
android:requestLegacyExternalStorage="true"