Default values for arguments when argument is null? - dart

Is there any way to get this to return "default" without writing out special functions to check the argument and set it?
void main() {
Thing stuff = Thing(text: null);
print(stuff.text);
}
class Thing{
String text;
Thing({this.text: "default"});
}
I have a map coming in from Firebase and sometimes values will be null and I'd like my class to use its default values when it is provided null.

Thing({text}) : this.text = text ?? 'default';
You will need to add this small snippet because default values in constructors only work if there is no value specified.
The ?? null-aware operator will only use the 'default' value if the value that is being passed is actually null (which will also be the case if no value is specified).

Related

is it possible to return a default value when using enum in dart

Now I am define a enum in dart like this:
enum LoginType {
PHONE,
WECHAT
}
extension ResponseStatusExtension on LoginType{
static const statusCodes = {
LoginType.PHONE: 1,
LoginType.WECHAT: 2,
};
int get statusCode => statusCodes[this];
}
I am upgrade to flutter 2.0.1 and support null safety and now it tell me :
A value of type 'int?' can't be returned from the function 'statusCode' because it has a return type of 'int'.
but I want to make it return a default not null value to make the code rubust and did not have to handle null when using this enum. what should I do to make it return a default value? is it possible?
The reason for your error is that the [] operator on Map is nullable since it has this behavior:
The value for the given key, or null if key is not in the map.
https://api.dart.dev/stable/2.12.2/dart-core/Map/operator_get.html
If you are sure your Map always contains the requested key you can add a ! after the use of [] operator like this:
int get statusCode => statusCodes[this]!;
This will make a null-check at runtime and fail if a null value is returned. But this should not be a problem if you are sure null is never returned from the Map.
Bonus tip
If you want to be able to have a default value returned from a Map in case the Map does not contain a given key you can add the following extension to Map:
extension MapDefaultValue<K, V> on Map<K, V> {
V get(K k, V defaultValue) => containsKey(k) ? this[k] as V : defaultValue;
}
Notice that defaultValue must be a compatible type for key in the Map so you cannot use null as defaultValue if null are not allowed as a value in the Map.

A value of type 'T?' can't be assigned to a variable of type 'T'

I am trying to assign to an int value, however, I get this error:
A value of type 'int?' can't be assigned to a variable of type 'int'
The line causing this compile-time error is the following:
int number = someFunction();
The problem here is that the value returned from someFunction is nullable and trying to assign that value to a non-nullable variable is a compile-time error (null-safety was introduced in Dart 2.7).
You need to check for null using a != null condition.
Example
void exampleFunction<T>(T? input) {
T result = input; // <- ERROR here
print(result);
}
In this example, input is nullable and thus cannot be assigned to the non-nullable variable result.
Solution
The given example problem can be solved like this:
void exampleFunction<T>(T? input) {
if (input != null) {
T result = input;
print(result);
}
}

How to create nullable variable in Dart

I created a model class, this is one of my a variable in model class
Datetime hotel_effect_open_date
but JSON response hotel_effect_open_date is null, getting an error in my application. and I modified to DateTime to String, it's working. In API created in the .net core, it looks like this,
Nullable<DateTime> hotel_effect_open_date
How to create a nullable variable in DART language?
Now Dart is in the process of redesigning its type system. So that expression of that type can be either nullable or non-nullable. Something like this:
type? variable; // variable can be null.
Example:
int? a; // a can now be null.
Reference: Dart nullability syntax decision
TLDR:
int? aNullableInt = null;
Detailed explanation:
Dart 2... and above
documentation:
https://dart.dev/null-safety
With null safety, all of the variables in the following code are
non-nullable:
// In null-safe Dart, none of these can ever be null.
var i = 42; // Inferred to be an int.
String name = getFileName();
final b = Foo();
To indicate that a variable might have the value null, just add ? to
its type declaration:
int? aNullableInt = null;
Dart <2
DateTime example;
example = null;
Uninitialized variables have an initial value of null. Even variables with numeric types are initially null, because numbers—like everything else in Dart—are objects.
int lineCount;
assert(lineCount == null);

How do I get the default value of an optional parameter, using Dart's analyzer API?

I'm using Dart's analyzer API, which allows me to introspect Dart code.
Here is some example code:
void soIntense(anything, {bool flag: true, int value}) { }
Notice how the flag parameter has a default value of true.
How can I get the default value, assuming I have an instance of ParameterElement?
Here's the best way that I found. I'm hoping there's a better way.
First, check that there is a default value:
bool hasDefaultValue = _parameter.defaultValueRange != null &&
_parameter.defaultValueRange != SourceRange.EMPTY;
Then, you can use a ParameterElement's defaultValueRange.
SourceRange range = _parameter.defaultValueRange;
return _parameter.source.contents.data.substring(range.offset, range.end);
In english:
Get the parameter element's Source's content's data's substring.

Object.ReferenceEquals returns incorrect results (in Silverlight 3 at least)

I just discovered a very strange behaviour. I have a class with a string property. In the setter of this property I compare the old value with the new value first and only change property if the values differ:
set
{
if ((object.ReferenceEquals(this.Identifier, value) != true))
{
this.Identifier = value;
this.RaisePropertyChanged("Identifier");
}
}
But this ReferenceEquals almost always returns false! Even if I call object.ReferenceEquals("test", "test") in Quick Watch I get false.
How is this possible?
That's because strings are immutable in C#:
The contents of a string object cannot
be changed after the object is
created, although the syntax makes it
appear as if you can do this.
Since you can't modify an existing string reference, there's no benefit in reusing them. The value passed to your property setter will always be a new string reference, except maybe if you do this.Identifier = this.Identifier;.
I'll try to clarify with an example:
string s = "Hello, "; // s contains a new string reference.
s += "world!"; // s now contains another string reference.

Resources