as you maybe seen before in Effective Dart: Usage
(https://dart.dev/guides/language/effective-dart/usage)
you see :
optionalThing?.isEnabled ?? false;
I know val??other is an alternative of val == null ? other : val
but I don't understand what is ?.
The ?. operator is part of the null-aware operators. This is used in the following context:
if(object != null)
{
object.method1();
}
The above can be written as object?.method1();
So a code bool isEnabled = optionalThing?.isEnabled ?? false; will translate to following:
bool isEnabled;
if(optionalThing != null)
isEnabled = optionalThing.isEnabled;
else
isEnabled = false;
That question mark is for optionals. You can find this in swift, Kotlin and typescript as well.
Following your example optionalThing?.isEnabled is the same as:
optionalThing == null ? null : optionalThing.isEnabled;
This lets you call a method or property of an object without having to check whether the object is null. In case the object is null it would return null instead of crashing and that property or method would not be called.
Related
I am trying to check value using if but the app crash on that line. I am using flutter.
if (value == null || value.isEmpty || !value.contains('#')) {
return 'Please enter a valid email.';
}
getting that
Error: Property 'isEmpty' cannot be accessed on 'String?' because it is potentially null.
Try accessing using ?. instead.
Please update Flutter and Dart to the latest versions. The error you describe should not happen.
This example is compiling and running perfectly fine, printing:
Please enter a valid email.
null
With no warnings or errors.
String? isValid(String? value) {
if (value == null || value.isEmpty || !value.contains('#')) {
return 'Please enter a valid email.';
}
return null;
}
void main() {
print(isValid(null));
print(isValid('valid#email.example.com'));
}
Replace
value.isEmpty
With
(value.toString()).isEmpty
Do this instead
if((value != null && (value.isEmpty() ||
!value.contains('#'))) || (value ==
null)){
}
If you have declared a variable to be nullable and did not assign a default value, and later you want to use isEmpty on that variable, you must first check that the variable is not null before checking if it's empty or not.
Adding my comment as answer so you can have better view of it:
if (value == null || ( value?.isEmpty ?? true ) || (!value?.contains('#') ?? true )) {
return 'Please enter a valid email.';
}
YOU HAVE TO REPLACE SOME OF YOUR CODE
value.isEmpty
REPLACE IT WITH
( value?.isEmpty ?? true )
I'm using New Input system on my game and I'm having this error
NullReferenceException: Object reference not set to an instance of an object
PauseMenu.Update ()
pointing to this line:
if (gamepad.startButton.wasPressedThisFrame || keyboard.pKey.wasPressedThisFrame)
whenever the gamepad is not connected.
void Update()
{
var gamepad = Gamepad.current;
var keyboard = Keyboard.current;
if (gamepad == null && keyboard == null)
return; // No gamepad connected.
if (gamepad.startButton.wasPressedThisFrame || keyboard.pKey.wasPressedThisFrame)
{
if (GameIsPaused)
{
Resume();
}
else
{
Pause();
}
}
}
How can I fix this?
The issue is that the exit condition requires that both keyboard and gamepad are null. In the case that gamepad is null and keyboard is not (or the other way around), an attempt is made to access a member of the null object.
You can resolve the issue by comparing each object against null before accessing its properties.
if ((gamepad != null && gamepad.startButton.wasPressedThisFrame) ||
(keyboard != null && keyboard.pKey.wasPressedThisFrame)
)
{
// Pause / Resume
}
You could also use the null conditional operator ? in each condition. When the preceding object is null, the resulting value is null. Then using the null coalescing operator ?? we convert this null value to a bool (false in this case because a null button cannot be "pressed").
if (gamepad?.startButton.wasPressedThisFrame ?? false ||
keyboard?.pKey.wasPressedThisFrame ?? false)
Can this code snippet be simplified on the second line?
From:
GetBuilder<ProductController>(builder: (productController) {
return productController.reviewedProductList == null || productController.reviewedProductList.length != 0
? CategoryDrinksView(productController: productController, isPopular: true)
: SizedBox();
})
To:
GetBuilder<ProductController>(builder: (productController) {
return productController.reviewedProductList?.length != 0
? CategoryDrinksView(productController: productController, isPopular: true)
: SizedBox();
})
The IDE doesn't return any errors and everything seems to work, but I would like to know if this is common in Dart and can be considered good practice.
I don't think it's a good idea. You may get a 'NoSuchMethodError: The getter 'length' was called on null' error, if the value of reviewedProductList was null. So keep the double checking
I have 2 newbie questions here.
1st question: Why it won't go through the statement print('it will NOT go here.');
I got the error Null check operator used on a null value. But I already added ? to say that it can be null in the Price? class.
2nd question: Why this statement if (_price != null) shows The operand can't be null, so the condition is always true. But I know that it can be null since it is possible that it is not existing. Please help me understand what's going on. Thanks!
This is my code:
DocumentReference<Map<String, dynamic>> docRefPrice =
db.collection('dataPath').doc('ThisIsNotExisting');
print('it will go here - 1');
final DocumentSnapshot<Map<String, dynamic>> documentSnapshotPrice = await docRefPrice.get();
print('it will go here - 2');
Price? _price = Price.fromFirestore(documentSnapshotPrice);
print('it will NOT go here.');
if (_price != null) {
print('_price is not null');
}
else { print('_price is null');
return false;
}
Edit add fromFirestore:
factory Price.fromFirestore(DocumentSnapshot<Map<String, dynamic>> doc) {
Map data = doc.data()!;
return Price(
price1: data['text1'],
price2: data['text2'],
);
}
This is the link that I tried to understand: https://dart.dev/codelabs/dart-cheatsheet
Regarding your first question, the function fromFirestore is what's causing the error, add the code for it to your question.
the second question, _price won't be null cause Price.fromFirestore(documentSnapshotPrice); is a constructor so it will return a Price object and never null.
Edit
Most probably this line is the reason for the error: Map data = doc.data()!; remove the ! and make the Map nullable and handle this case
I will need the Price class code to write the code but here is the idea
factory Price.fromFirestore(DocumentSnapshot<Map<String, dynamic>> doc) {
Map? data = doc.data();
return Price(
price1: data == null ? null : data['text1'], // price1 must accept null in this case
price2: data == null ? null : data['text2'], // price2 must accept null in this case
);
}
Got the following errors and don't know how to update the code to solve it.
Error: Can't use an expression of type 'Function?' as a function because it's potentially null.
'Function' is from 'dart:core'.
Try calling using ?.call instead.
PageName nextPage = pageName_pageFunction_mapPageName.welcomePage;
PageName nextPage2 = pageName_pageFunction_mapnextPage;
The code:
enum PageName {
welcomePage,
register,
login,
editProfile,
showProfile,
resetPassword,
errorUserExists,
}
Map<PageName, Function> pageName_pageFunction_map = {
PageName.welcomePage: showWelcomePage,
PageName.register: showRegisterPage,
PageName.login: showLoginPage,
PageName.editProfile: showEditProfile,
PageName.showProfile: showUserProfile,
PageName.resetPassword: showResetPassword,
PageName.errorUserExists: showErrorUserExists,
};
void main() {
PageName nextPage = pageName_pageFunction_map[PageName.welcomePage]();
if (nextPage != null) {
while (true) {
PageName nextPage2 = pageName_pageFunction_map[nextPage]();
if (nextPage2 != null) {
nextPage = nextPage2;
}
}
}
}
Can you help me? Thank you
The error message tell that you can't execute a function because this one might be null, and if you execute a function on a null value it will break the program. You have two solution :
First you can make sure that your function isn't null with a test :
if (myFunction != null) {
myFunction()
}
Or you can tell the compiler that your function is not null with the ! operator
myFunction!()
Error: Can't use an expression of type 'Function?' as a function
because it's potentially null.
When you look up one of your functions from the map like pageName_pageFunction_map[PageName.welcomePage] you get a value of type Function?. This is because if you enter a key which does not have a corresponding value, you will get back null from the expression.
The following error message gives you a suggestion on how to solve this problem.
'Function' is from 'dart:core'. Try calling using ?.call instead.
PageName nextPage = pageName_pageFunction_mapPageName.welcomePage;
PageName nextPage2 = pageName_pageFunction_mapnextPage;
You can place ?.call directly before the argument list () to safely call the function;
pageName_pageFunction_map[PageName.welcomePage]?.call();