named parameter in Dart - dart

Good day, I am trying to apply named parameter {num phone} to the below example:
main(){
showInfo("abc#mail.com", "Fatima");
}
String showInfo(String email, String name, {num phone}) {
print(email);
print(name);
print(phone);
return "$email : $name : $phone";
}
but I receive the error:
Error: The parameter 'phone' can't have a value of 'null' because of its type 'num', but the implicit
default value is 'null'.
Try adding either an explicit non-'null' default value or the 'required' modifier.
Future<String> showInfo(String email, String name, {num phone}) async {
^^^^^
your help is appreciated.

You marked the parameter as a num, which means it cannot be null. However, the default for named parameters that are not used is null, so you cannot have a named parameter that is optional with a default value of null with a datatype that does not accept null.
One option is to give it a default value other than null:
String showInfo(String email, String name, {num phone = 0})
Another option is to make it a named, but required parameter, so it will never get a default value:
String showInfo(String email, String name, {required num phone})
Another alternative is to actually keep the phone optional:
String showInfo(String email, String name, {num? phone})
Some additional wisdom: phone numbers can start with leading zeroes that are important and should not be deleted on saving it. You cannot use num for a phone number, you will have to use string.

The error is pretty clear, you have to pass a value to the phone parameter or add a default value. This is due to the introduction of Null Safety in Dart 2.12.
You can pass a value like this :
showInfo("abc#mail.com", "Fatima", phone: 0);
Or add a default value to the phone parameter :
String showInfo(String email, String name, {num phone = 0}) {
print(email);
print(name);
print(phone);
return "$email : $name : $phone";
}
If you want, you can use Dart <2.12 to avoid Null Safety, your code should work properly then.

Related

'String?' can not convert to 'String' in dart

A value of type 'String?' can't be assigned to a variable of type 'String'.
Try changing the type of the variable, or casting the right-hand type to 'String'.
This error message i got when i run this code.
This is a simple user input code on dart.
var person = ['abc', 'qwe', 'dfg'];
stdout.write('Enter Index : ');
String p = stdin.readLineSync(); //Error
int per = int.parse(p);
per > person.length
? stderr.write('Index does not exist')
: stdout.write('Person ${person[per]}');
}
Seems like readLineSync() returns nullable type. But you declare variable p as non-nullable. Either declare p as nullable: String? instead of String or make readLineSync() return default value if null:
String p = stdin.readLineSync() ?? "";// will return empty String if method readLineSync() returns null.
First of all check the null safety documentation, you'll learn everything you need to know
https://dart.dev/null-safety/understanding-null-safety
readLineSync returns a value of Type String? Meaning the return value must be a nullable String.
p is of type String and therefore expects a String (not a nullable String). the trick here is to cast stdin.readLineSync() to String:
String p = stdin.readLineSync() as String;
String p = stdin.readLineSync()!; #shorthand syntax
On top of that, your code needs some improvements. What if p can't be cast into an integer? One way to handle this is to add a try block and catch any FormatException.

is there a way to perform optional casting in Dart?

in Swift or Kotlin I can do something like this
var fullName = myMap["fullName"] as? String
then as a result that fullName data type will be optional String ( String? ).
I need to get optional type after type checking like that
I can't directly perform null coalescing operator to that map, because dart will give weird result. for example like this
// 'data' is Map<String, dynamic>
final fullName = data["fullname"] ?? "John Doe";
final double myNumber = fullName;
as you can see, the IDE will not show an error at all, I expect that fullName will be a String, so it will have an error when I assign a String to myNumber that require double.
If you know in advance that data["fullname"] is a String, then you could do:
final fullName = (data["fullname"] ?? "John Doe") as String;
If data["fullname"] turns out not to be a String at runtime, you'll get a runtime exception from the cast failure. If that's something you need to handle, then you could easily make a trivial helper function that checks if a dynamic value is the desired type first and that returns null if it isn't:
T? tryCast<T>(dynamic object) => object is T ? object : null;
final fullName = tryCast<String>(data["fullname"]) ?? "John Doe";
and now fullName is statically known to be a String, and accidentally assigning it to a double will be a compile-time error.
The safe nullable cast operator known from Kotlin currently doesn't exist in Dart but it soon might.
In your case though, why not simply write
String? fullname = myMap["fullname"];
The nullable cast operator as? in Kotlin yields null if myMap["fullname"] contains anything but a non-null String. As long as you're only dealing with Strings or null, the above works just fine. (And if there's anything but a String or null it crashes, which is probably better than just continue on with null in most situations)

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.

Passing Object.Attr to function

Usually, a reference to an Object's Attribute Value returns that value.
Object o = current Object
display o."Object Text"
However, if I pass that reference to a function that expects a string parameter, I get an error.
string displaySomeString(string s) {
display s
}
Object o = current Object
displaySomeString(o."Object Text")
I get this result from the debugger:
-E- DXL: incorrect arguments for function (displaySomeString)
-I- DXL: All done. Errors reported: 1. Warnings reported: 0.
What gives? How do I robustly pass an Attribute value into a function?
Here's my suspicion. If you're passing the object attribute value directly in the function call--
displaySomeString(o.attr)
--instead try passing it with an empty string at the end:
displaySomeString(o.attr "")
Or set the attribute value as something like
string v = o.attr
and then pass v in as
displaysomeString(v)
and I think it might work. o.attr really isn't a string, but a derived type, and concatenating an empty string at the end casts it to a string.

Default values for arguments when argument is null?

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).

Resources