Undefined name 'Utils' error in catch exception - flutter

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

Related

Flutter - Riverpod Future Provider: How to keep old data when error occurs

This is my usecase:
data is downloaded
final dataProvider = FutureProvider<MyModel>((ref) async {
return fetchData();
});
and it's used like this within widget's build method:
ref.watch(dataProvider).when(
data: DataWidget(data),
error: ErrorWidget(),
loading: LoadingWidget())
user has option to refresh the data:
ref.refresh(dataProvider.future);
But when there is an error (for example phone is in airplane mode) error is provided so DataWidget is lost and replaced with ErrorWidget... Is there a way using Riverpod to provide/keep existing data instead of error ? I believe it's common scenario, but I didn't find any elegant solution for this problem. I've also read documentation too, but didn't find anything helpful related to this. Am I missing something ? (I'm new to Riverpod) Thank you
Preserving the previous data on refresh is behavior as part of 2.0.0.
Although there were some bugs that you may have encountered. Make sure youre using 2.1.3 or above, which should fix all the issues related to this.
As for using when to show the previous data/error, you can use various flags:
asyncValue.when(
// show previous data/error on loading
skipLoadingOnReload: true,
// show previous data if there's an error
skipError: true,
loading:...,
data:...,
error: ...,
)
In the new version of Riverpod (as of v.2.1.0), you can do this:
asyncValue.when(
skipLoadingOnReload: false,
skipLoadingOnRefresh: true,
skipError: false,
data: DataWidget(data),
error: ErrorWidget(),
loading: LoadingWidget(),
)
You can see more details here.

flutter access call logs

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

Unexpected text 'await' when opening database with Flutter

I'm following the Persist data with SQLite tutorial from the Flutter Dev website, and I'm trying to open a database connection using async, but I keep getting the error Unexpected text 'await'. Even when I copy the code directly from the tutorial I'm still getting the same error.
This is my full file:
import 'dart:async';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
// Open the database and store the reference.
final Future<Database> database = openDatabase(
join(await getDatabasesPath(), 'doggie_database.db'),
);
As far as I can tell I'm using the keyword correctly, so why is the compiler complaining?
I'm using Dart 2.7.0-dev.2.1 if that makes a difference.
This seems like an issue with asynchronicity. It's strange that an example from the official documentation is leading you into this mistake. Directly assigning a variable outside of a method that would need to be async. Try this:
final Future<Database> database = getDatabasesPath().then((String path) {
return openDatabase(join(path, 'doggie_database.db'));
});
For future reference, the reason why the OP's code wasn't working was because he was running it outside of the main() Flutter method, which is async in the example provided by the Flutter documentation: https://flutter.dev/docs/cookbook/persistence/sqlite#example

Office JavaScript API: selecting a range in Word for Mac

I'm working on a side project using the Microsoft Office JavaScript APIs. I have some functionality working to select a range in order to scroll to a particular position within a document. This works as expected in Office for the web, but in Office for Mac I get the following error when calling context.sync().then():
Unhandled Promise Rejection: RichApi.Error: ItemNotFound
I can't find any documentation on that particular error, and I'm not sure how to troubleshoot what I might be doing wrong. What am I missing? Like I said, this works in the web interface.
Here is minimal sample of code that demonstrates the problem:
function UI(context) {
this.context = context;
}
UI.prototype.initialize = function() {
var paragraphs = this.context.document.body.paragraphs;
this.context.load(paragraphs);
document.querySelector('button').addEventListener('click', () => {
this.context.sync().then(() => {
this.goToRange(paragraphs.items[0]);
});
});
};
UI.prototype.goToRange = function(range) {
range.select();
this.context.sync();
};
document.addEventListener('DOMContentLoaded', () => {
Office.onReady(() => {
Word.run(context => {
return context.sync().then(() => {
new UI(context).initialize();
});
});
});
});
The only thing I can think of is that maybe the reference to the paragraph client object becomes "stale" in some sense, perhaps based on some resource limits that are lower in the Mac application than in the online interface? (That would be counterintuitive to me, but it's the only thing that comes to mind.)
I think I figured out the problem. I stumbled upon a hint while putting together the minimum code sample in the question; I removed a little too much code at first and encountered the following error:
Unhandled Promise Rejection: RichApi.Error: The batch function passed
to the ".run" method didn't return a promise. The function must return
a promise, so that any automatically-tracked objects can be released
at the completion of the batch operation.
I believe the issue is that, at least in Word for Mac, you can't use the context object provided by Word.run in an asynchronous event listener. I'm guessing this is because, as the above error states, some state has been released after resolving the promise returned. I can get the code to work by adding a dedicated call to Word.run (and using the fresh context provided) inside the event listener.
It is still a little odd that it works just fine in the browser. Presumably, the same state is not released as aggressively in the browser-based version.

How to perform soft assert in protractor cucumber

defineSupportCode(({Given, When,Then})=>{
When('click on search button', async () =>{
await browser.actions().sendKeys(protractor.Key.ENTER).perform();
await browser.sleep(3000)
await browser.actions().sendKeys(protractor.Key.ENTER).perform();
await browser.sleep(3000)
let element1 = element(by.xpath("//h3[text()='Selenium - Web Browser Automation']"))
await expect(element1.isDisplayed()).to.eventually.be.false;
});
Then('it should show search result', async () =>{
let element2 = element(by.xpath("//h3[text()='Downloads - Selenium']"))
await expect(element2.isDisplayed()).to.eventually.be.true;
});
})
My last then block was skipped.But I want to continue my all test steps even if it is pass or fail (then definitely i think i have to use soft assert).In testng we have a class called softassert. Is there something available here as well similar to that one. I am using chai package for assertion purpose
TIA
Background:
This is not a protractor or cucumber issue, it is actually chai(well it looks like you are using chai from your code snippet but feel free to correct me if I'm wrong).
Issue:
After reviewing chai docs https://www.chaijs.com/api/assert/ it looks like they do not support the concept of soft asserts like some other assertion frameworks.
Solution 1:
The only workaround I can think of is to wrap your assertion in a try catch and store the error received from the assertion in your world instance, then in your after hook throw the errors.
Solution 2:
Use a library that does support soft asserts. From a quick search, I see https://www.npmjs.com/package/soft-assert but FYI I have not tried this library
Notes:
One bad thing about this is that screenshots may capture incorrect information.