flutter access call logs - flutter

i want to get my call logs and i used call logs package and on button click, i call tthis function
void calllog() async{
Iterable<CallLogEntry> entries = await CallLog.get();
for (var item in entries) {
print(item.name);
}
}
but its shooting me an error like this
[ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: PlatformException(INTERNAL_ERROR, Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference, null, null)
PS: i am using this package: call_log: ^3.0.3

<uses-permission android:name="android.permission.READ_CALL_LOG" />
Add this to your android/app/src/main/AndroidManifest.xml file just under the first < manifest> tag.

At first you need to add permission to manifest so operating system will know that your app can ask for log reading. for that, you need to go to:
android/app/src/main/AndroidManifest.xml
android/app/src/debug/AndroidManifest.xml
You need to paste this permission under manifest<>
<uses-permission android:name="android.permission.READ_CALL_LOG" />
So, now you have to ask user to grant this request. for that you can use this plugin permission_handler
You can ask for permission like this:
void getPermissionUser() async {
if (await Permission.phone.request().isGranted) {
getLog();
} else {
await Permission.phone.request();
}
}
Now you can read call logs without any errors.

If the permission to access call logs was denied, this error would occur

This package is not supported anymore and not working for me.
after searching along I found this package from the flutter plugin
and I made my own fork and migrated it to null safety and it's now working
check it out as a working alternative

Related

Undefined name 'Utils' error in catch exception

I am working on Flutter Firebase send verification email page, but I am getting the Undefined name Utils error after adding a catch error exception. Below is the snippet of the code:
Future sendVerificationEmail() async {
try {
final user = FirebaseAuth.instance.currentUser!;
await user.sendEmailVerification();
setState(() => canResendEmail =` false);
await Future.delayed(const Duration(seconds: 5));
setState(() => canResendEmail = true);
}
catch (e) {
Utils.showSnackBar(e.toString());
}
}
I could be wrong, but I think whoever wrote that code also wrote a Utils class with that function as well. It's not part of any standard library. And the exact implementation we can't know. Obviously it's some helper method to show a Snackbar. It usually requires a BuildContext, but you could check out How to show snackBar without Scaffold to see alternatives.
And a quick Google search makes me think that you simple copied that code from How to use google login in flutter and bypass emailverification since it has the exact same method. I apologize if that's not the case. My advice is to not simply copy pasting code without understanding what's happening. Especially code that is not part of a guide.
In any case, the code that doesn't work shows a message to the user through a Snackbar in case an exception happens. Which isn't really a user-friendly message, so it might be not that great to write it like that anyway.
I think you haven't added
import 'package:basic_utils/basic_utils.dart';
Or, make sure you added this in your pubspec.yaml file:
dependencies:
basic_utils: ^4.2.2

How can I initialize a empty file without giving it a path in flutter after null safety is enabled

I was working on a project for which I require the user to select a file from his/her device. The way I did it before flutter updated to enable null safety was that I would initialize an empty file and after the user picks the file the empty file gains the path of the selected file. This was the code to do it -
File myfile;
Future<void> _takePicture() async {
FilePickerResult? result =
await FilePicker.platform.pickFiles(type: FileType.image);
if (result != null) {
PlatformFile file = result.files.first;
setState(() {
myFile = File(file.path.toString());
});
But after I updated flutter to 2.5.2 it started giving an error , 'Non-nullable instance field 'myFile' must be initialized.'. My IDE suggests adding a late modifier before initializing the file, but after picking the file the app crashes due to that. Is there any way around this?
Please help
If your variable can be null, then just make it nullable:
File? myfile;
Null-Safety is a great feature to let you see faster and more effective when something can or cannot be null. But some variables can be null. That's totally fine. All null safety requires is that you declare them as such using the question mark as seen above.

How can I delete an image I have stored in Google Coud Storage Bucket in Flutter? (Not Firebase Cloud Storage)

I have the image's public link. I'm thinking of the gcloud flutter package https://pub.dev/packages/gcloud but I can't really find anything that shows how to do exactly what I'm trying. Advanced Thanks.
PLEASE, I'm not talking about Firebase Cloud Storage.
To delete a file, first create a reference to that file. Then call the delete() method on that reference, which returns a Promise that resolves, or an error if the
Promise rejects.
import { getStorage, ref, deleteObject } from "firebase/storage";
const storage = getStorage();
// Create a reference to the file to delete
const desertRef = ref(storage, 'images/desert.jpg');
// Delete the file
deleteObject(desertRef).then(() => {
// File deleted successfully
}).catch((error) => {
// Uh-oh, an error occurred!
});

Flutter: Error: MissingPluginException(No implementation found for method getTemporaryDirectory on channel plugins.flutter.io/path_provider)

I'm using Flutter-web and I want to export a pdf. I'm using the pdf package and i'm trying to implement a simple example from their documentation. To be more specific, I have a file called export_pdf.dart and the code inside it is the following.
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart';
import 'package:universal_io/io.dart';
import 'package:path_provider/path_provider.dart';
exportPdf() async {
final pdf = Document();
pdf.addPage(Page(
pageFormat: PdfPageFormat.a4,
build: (Context context) {
return Center(
child: Text("Hello World"),
); // Center
})); // Page
final output = await getTemporaryDirectory();
final file = File("${output.path}/example.pdf");
await file.writeAsBytes(await pdf.save());
}
When i'm calling the exportPdf() function by clicking a button, i'm getting the following error.
Uncaught (in promise) Error: MissingPluginException(No implementation
found for method getTemporaryDirectory on channel
plugins.flutter.io/path_provider)
I've been searching for this issue for a long time, but no solution has fixed this one.
Even though the path_provider package is imported, the getTemporaryDirectory() is never called, like it doesn't exist.
I need also to mention that i'm using universal_io, instead of dart:io, because i'm using flutter_web.
This error shows up for every function i'm calling and exists inside the path_provider/path_provider.dart file. I've also added inside path_provider/path_provider.dart a simple print function and i'm getting an error that the method is not found.
Thank you for your time.
Run these commands
flutter clean
flutter pub get
flutter run
Make sure after the first command, the build folder is removed.
I found out that this current package does not support file saving in web and it is suggested to use the printing plugin to print or share the file.

Flutter Firebase Cloud function can not be called

I am getting an error whilst using Firebase Cloud Functions when I try to call a callable function from Flutter.
flutter: caught generic exception
flutter: PlatformException(functionsError, Firebase function failed with exception., {message: NOT FOUND, code: NOT_FOUND})
Here is how I try to call the cloud function with using cloud_functions: ^0.4.2+3
import 'package:cloud_functions/cloud_functions.dart';
_check(String id) async {
HttpsCallable callable = CloudFunctions.instance
.getHttpsCallable(functionName: 'checkUserFavorites');
try {
final HttpsCallableResult result = await callable.call(
<String, dynamic>{
'id': id,
},
);
print(result.data);
} on CloudFunctionsException catch (e) {
print('caught firebase functions exception');
print(e.code);
print(e.message);
print(e.details);
} catch (e) {
print('caught generic exception');
print(e);
}
}
I have experienced similar issues, and with few days of debugging and experimenting I found the solution only after studying the source code of Cloud Functions Plugin for Flutter.
When you deploy Firebase Cloud function, you can choose any region of preference (closer to your application the better). For example
// using DigitalOcean spaces
exports.generateCloudImageUrl = functions
.region('europe-west3')
.https.onCall((reqData, context) => {
...
}
When you want to call this function from Flutter app, you must specify the region, otherwise all goes to us-central1 which is default. See example code on how to use a function deployed in a specific region
final HttpsCallable generateCloudImageUrl = new CloudFunctions(region: "europe-west3")
.getHttpsCallable(functionName: 'generateCloudImageUrl');
// NB! if you initialize with 'CloudFunctions.instance' then this uses 'us-central1' as default region!
see cloud_function source for init.
Update, as of recent release, you can initialize as below;
FirebaseFunctions.instanceFor(region: "europe-west3").httpsCallable(
"generateCloudImageUrl",
options:
HttpsCallableOptions(timeout: const Duration(seconds: 30)));
Cloud functions are supported in the regions that you are currently running them, according to the Cloud Functions Location Documentation, but not in all regions.
According to what you shared in the comments, I would say that there are 3 cenarios to your issue:
europe-west1: The function is probably out of date, since you are getting an unespected data format error, which suggest that it expects different data/format than your default function.
europe-west2: The function is not deployed in this region, this is hinted in the error message message: NOT FOUND.
Default Function (unknown region): This is the most recent version of the function, on a region different than europe-west1 and europe-west2, and it accepts the call
with the data in the format that you are sending.
NOTE: You can check which regions you currently have your cloud function deployed on the cloud functions dashboard, as you can see on the example image below:
Also, I suspect that the default region you using is us-central1, since according to the documentation:
By default, functions run in the us-central1 region
To fix your issue, I suggest that you redeploy your current version of the function to the europe-west regions that you intend to use.
There are three reasons this error mostly happens:
1. Call the correct function:
Make sure to call the correct function in its full name (visible when you start a local emulator). Espacially if you have additional exports of files in your index.js file make sure to call the export name as well.
Syntax: serverLocation-optionalExportParent-yourFunction
Example: us-central1-post_functions-updateShare
Note that the server location can also be configured in your instance
2. Emulator: Same WIFI
Make sure to be connected to the same wifi, when using the emulator. Otherwise, any call will end in unvailablity resulting in
Unhandled Exception: [firebase_functions/unavailable] UNAVAILABLE
3. Emulator: Correct host configuration
To connect to a physical device the host at all emulators at your firebase.json must be configured: Simply add "host": "0.0.0.0".
Now the host in flutter needs to be your ip-adress of the computer. More on that here
In my case, in addition to the regional issue, what really solved to me was to include the script below in index.html:
<script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-functions.js"></script>