Flutter pick image camera or gallery exception - flutter

I have a Flutter project in which I am trying to put MLKit for text OCR.
I have crated a standalone Flutter project which works fine with MLKit. However when I put the same code and dependencies to my existing Flutter project it is not working as expected.
Below are the issues I am getting when trying to choosing the image...
When I click on the gallery to choose the image it throws exception.
final file = await ImagePicker.pickImage(source: imageSource);
if (file == null) {
throw Exception('File is not available');
}
When I am trying to choose camera it asks for the permission for the first time and then app gets closed.... throws " java.lang.NullPointerException: 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"
Once these exceptions thrown every subsequent tries it throws exception "PlatformException(already_active, image picker is already active, null)"
cupertino_icons: ^0.1.2
firebase_auth: ^0.8.0+1
cloud_firestore: ^0.9.0
firebase_core: ^0.3.0
intl_translation: ^0.17.2
firebase_messaging: ^3.0.0
http: ^0.12.0+1
xml: ^3.3.1
firebase_storage: ^2.0.0
uuid: ^1.0.3
shared_preferences: ^0.5.0
flutter_staggered_grid_view: ^0.2.7
google_sign_in: ^4.0.0
flutter_signin_button: ^0.2.5
mlkit: ^0.9.0
path_provider: ^0.5.0+1
image_picker: ^0.5.0+3
I have followed below blog in order to implement MLKit https://medium.com/flutter-community/flutter-text-barcode-scanner-app-with-firebase-ml-kit-103db6b6dad7
Thank you

use image_picker plugin
var imageSource;
if (source == CAMERA_SOURCE) {
imageSource = ImageSource.camera;
} else {
imageSource = ImageSource.gallery;
}
try {
final file = await ImagePicker.pickImage(source: imageSource);
if (file == null) {
throw Exception('File is not available');
}

Try cleaning your app, use Flutter clean command.
Many times I have faced this sort of issues where there were no issue related to code and still something went wrong, but somehow Flutter clean tends to help resolve the issue.

You need to delete the build folder in your project. Once you do it and you start your project again, it will work.

First, the problem could be with the permissions, you need to add permission_handler for accessing the hardware like camera or storage etc.
Secondly try other application for camera other than the default app in our phone.

Related

The method 'watchPerformance' isn't defined for the type 'IntegrationTestWidgetsFlutterBinding'

I'm currently doing the integrated_test codelab on https://codelabs.developers.google.com/codelabs/flutter-app-testing/#6.
I'm on step 6 where I have to test the performance of the test_app:
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:testing_app_codelab/main.dart';
import 'package:testing_app_codelab/testing_app.dart';
void main() {
group('Testing App Performance Tests', () {
final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized()
as IntegrationTestWidgetsFlutterBinding;
binding.framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.fullyLive;
testWidgets('Scrolling test', (tester) async {
await tester.pumpWidget(TestingApp());
final listFinder = find.byType(ListView);
await binding.watchPerformance(() async { // error is here
await tester.fling(listFinder, Offset(0, -500), 10000);
await tester.pumpAndSettle();
await tester.fling(listFinder, Offset(0, 500), 10000);
await tester.pumpAndSettle();
}, reportKey: 'scrolling_summary');
});
});
}
I've gone through the IntegrationTestWidgetsFlutterBinding documentation and watchPerformance() is a method of it(please check: https://api.flutter.dev/flutter/package-integration_test_integration_test/IntegrationTestWidgetsFlutterBinding/watchPerformance.html).
The error I get on VS code is:
The method 'watchPerformance' isn't defined for the type 'IntegrationTestWidgetsFlutterBinding'.
Try correcting the name to the name of an existing method, or defining a method named 'watchPerformance'.
When I run the Integration test on my Android phone I get this error:
Try correcting the name to the name of an existing method, or defining a method named 'watchPerformance'.
await binding.watchPerformance(() async {
I got the idea to solve this problem from this post Flutter / Dart package integration_test with null safety
The problem was that integration_test dependency doesn't support null-safety.
when you check which dependencies have null safety support using this command:
dart pub outdated --mode=null-safety
The output is:
Showing dependencies that are currently not opted in to null-safety.
[✗] indicates versions without null safety support.
[✓] indicates versions opting in to null safety.
Package Name Current Upgradable Resolvable Latest
direct dependencies:
integration_test ✗0.8.1 ✗0.8.1 ✗0.8.1 ✗1.0.2+3
dev_dependencies: all support null safety.
You are already using the newest resolvable versions listed in the 'Resolvable' column.
Newer versions, listed in 'Latest', may not be mutually compatible.
This means that it's legacy and doesn't have support.
To solve this I changed the pubspec.yaml from this:
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
provider: ^6.0.1
test: ^1.19.5
integration_test: ^0.8.1
dev_dependencies:
flutter_test:
sdk: flutter
Changed to this instead:
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
provider: ^6.0.1
test: ^1.19.5
dev_dependencies:
integration_test:
sdk: flutter
flutter_test:
sdk: flutter
After this, I ran flutter pub get on the terminal and the error disappeared.
Now when I hover over the watchPerformance() method I get this info:
Future<void> watchPerformance(Future<void> Function() action, {String reportKey = 'performance'})
package:integration_test/integration_test.dart
Watches the [FrameTiming] during action and report it to the binding with key reportKey.
This can be used to implement performance tests previously using [traceAction] and [TimelineSummary] from [flutter_driver]
This is a general programming error that will occur. I will put an answer in because the error description for these is often rubbish at telling you what is going on here.
The error is telling you the function called watchPerformance on the object IntegrationTestWidgetsFlutterBinding (a var here called binding), does not exist.
Does the function use a captial W instead of lower case? Take another look at the docs and check everything is spelled correctly etc.

Flutter: E/location_permissions: result object is null in Geolocator plugin

I am using Geolocator plugin in Flutter Project. I have added it Pubspecs.yaml file also added the permission in AndroidManifest file.
Pubspecs.yaml
dependencies:
http: ^0.12.0
flutter:
sdk: flutter
shimmer: ^1.0.1
font_awesome_flutter: ^8.8.1
geocoder: ^0.2.1
geolocator: ^5.3.1
Android Manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
I am using SDK 28 - compileSdkVersion 28
Here is the code for location access.
String _locationMessage = "";
void _getCurrentLocation() async {
print('location');
final position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
print(position);
setState(() {
_locationMessage = "${position.latitude}, ${position.longitude}";
});
}
When I call _getCurrentLocation() on Button Pressed. It is showing dialog box to allow location access in App with three option.
Allow all the time
Keep While-In-Use Access
Keep and Don't Ask Again
After selecting Keep While-In-Use Access it is giving below message in Debug console.
E/location_permissions( 7592): Flutter result object is null.
What am I doing wrong?
Also, I want to know will it ask all the times when we try to access location or it will be one time?
Edit
If I select Allow all the time then my app stop responding. I mean if press the button nothing happen. Also I need to uninstall it from phone and run it again then it start giving the prompt for permission.
Edit 2
One strange thing I found. If location service is stop/not enabled then I am getting null. If I manually enable location then it start giving me location.
I think it has something to do with the package that you are using (geolocator),
I've also faced the same issue, when I was following a lecture from youtube
so I've gone for some other popular package to get location
and it's documentation is very simple.

How to access Flutter environment variables from tests?

I've been using flutter_dotenv to load environment variables saved in .env throughout the application and it's worked just fine to date. As I'm trying to write tests though, I cannot seem to access these from a test file.
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
setUp(() async {
await DotEnv().load();
});
test('Incorrect password should be rejected', () {
var password = DotEnv().env['PASSWORD'];
// stuff
});
}
Result of running the test:
Shell: [flutter_dotenv] Load failed: file not found
Shell: [flutter_dotenv] No env values found. Make sure you have called DotEnv.load()
It just can't seem to find the .env file. I even made a copy of .env in the test directory but it didn't recognise that either.
I've tried using Platform.environment instead of flutter_dotenv to access the variable, but that didn't work either, returning null.
Apologies if I'm being silly here, it's my first time writing Flutter tests, but would appreciate advice.
Update:
This is what my pubspec.yaml looks like:
name: //name
description: //description
version: 1.0.0+3
environment:
sdk: ">=2.1.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^0.1.2
font_awesome_flutter: ^8.5.0
flutter_youtube: ^2.0.0
http: ^0.12.0+4
flutter_dotenv: ^2.1.0
google_fonts: ^0.3.7
photo_view: ^0.9.2
flutter_page_transition: ^0.1.0
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
assets:
- images/
- .env
Add TestWidgetsFlutterBinding.ensureInitialized(); as the first line of your test's main function.
flutter_dotenv is trying to access ServicesBinding mixin which interacts with your app's platform. You need to initialize this binding first before accessing it and the above line of code will ensure this initialization occurs before running your tests.
Your code should look like this:
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:flutter_test/flutter_test.dart';
void main() async {
TestWidgetsFlutterBinding.ensureInitialized();
await DotEnv().load();
setUp(() {
// anything else you need to setup
});
test('Incorrect password should be rejected', () {
var password = DotEnv().env['PASSWORD'];
// stuff
});
}
For those having an error of type FileNotFoundError, update flutter_dotenv. From version 5.0.1 there is new method called testLoad() that works as expected because it doesn't use rootBundle to load the file as an asset.

Flutter Image picker is already active, null exception

In my flutter project I am getting exception whenever I am trying to pickup an image either from Camera or Gallery using the image_picker plugin of flutter.
For the very first time it asks for the permission and when I allow the camera it throws
java.lang.NullPointerException: 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
After that, it throws an exception for every subsequent tries
PlatformException(already_active, Image picker is already active,
null)
If I try to choose the camera or gallery even after restarting the app.
var imageSource;
if (source == CAMERA_SOURCE) {
imageSource = ImageSource.camera;
} else {
imageSource = ImageSource.gallery;
}
try {
final file = await ImagePicker.pickImage(source: imageSource);
if (file == null) {
throw Exception('File is not available');
}
Below are the dependencies:
cupertino_icons: ^0.1.2
firebase_auth: ^0.8.1
cloud_firestore: ^0.9.0+1
firebase_core: ^0.3.0+1
firebase_messaging: ^3.0.1
firebase_storage: ^2.0.1
intl_translation: ^0.17.3
http: ^0.12.0+1
xml: ^3.3.1
uuid: ^2.0.0
shared_preferences: ^0.5.1+1
flutter_staggered_grid_view: ^0.2.7
google_sign_in: ^4.0.1
flutter_signin_button: ^0.2.5
image_picker: ^0.5.0+2
mlkit: ^0.9.0
path_provider: ^0.5.0+1
Thanks for your time! I also tried to upgrade my flutter to the latest version.
Finally I was able to resolve it.
I updated all my dependencies and flutter SDK and then I did Flutter clean and it started working..
Thanks all for your time and help
Change in android/build.gradle classpath 'com.android.tools.build:gradle:3.5.4'
This worked for me.
Anyway, I have the same issue when using Image Picker.
I have solved the trouble, it needs to provide permission to access the camera and storage memory on the release mode.
On Android:
Add lines on file src/main/AndroidManifest.xml: inside the manifest tag
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
On IOS:
Add lines on file Info.plist:
<key>NSPhotoLibraryUsageDescription</key>
<string>Allow access to photo library</string>
<key>NSCameraUsageDescription</key>
<string>Allow access to camera to capture photos</string>
Good luck, hope it will be useful!
I updated package from 0.5.4+3 to ^0.6.5+2 and that solved my problem.
If you read the changelog, you will see every issue fixes: https://pub.dev/packages/image_picker#-changelog-tab-
If you have channel based code i.e bridge between Native Android and Flutter..
In MainActivity
on Activity Result
..
try adding ..
super.onActivityResult(requestCode, resultCode, data)
Removing and Reinstalling application as stated in the comments is fix the problem.
In my case, I haven't given access to "Files". While connecting USB, give access as shown :
Please add this line in your MainActivity.kt class:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
super.onActivityResult(requestCode, resultCode, data);

Flutter | Dart : Target of URI does not exist

I am making my first Application to build an Android App with Flutter.
I am using Android Studio as IDE.
The problem is when I import the http package:
import 'package:http/http.dart' as http;
I get an error :
error: Target of URI doesn't exist: 'package:http/http.dart'.
(uri_does_not_exist at [flutter_crypto] lib\home_page.dart:3)
That's my code :
Future<List> getCurrencies() async{
String cryptoUrl = "https://api.coinmarketcap.com/v1/ticker/?limit=50";
http.Response response = await http.get(cryptoUrl);
return JSON.decode(response.body);
}
Thanks,
You need to add the HTTP dependency to pubspec.yaml as per below.
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
http: ^0.12.0
With the dependency added you then need to run the following command to update/install required packages:
flutter packages upgrade
Hope this helps
Make sure you have added the dependency to pubspec.yaml
dependencies:
http: ^0.12.0
You will also need to:
flutter packages get
For any upcoming problem with importing packages from dart please go to official Dart website packages and search for needed package and you will find solution up there.
for your issue go to:
https://pub.dartlang.org/packages/http
Installing tap https://pub.dartlang.org/packages/http#-installing-tab-
follow guide steps:
In pubspec.yaml file:# dependencies
dependencies:
http: ^0.12.0
flutter:
(NB: please make sure that http & flutter or any other attribute inside dependencies are aligned as above and they are at same line)
In terminal run below command:
$flutter packages get
run: dart pub --trace get --no-precompile in android srudio Terminal