Let's say, in Dart/Flutter you are designing a plugin API have a function like this:
static Future<void> startPlaying(Uint8List bytes) async {
_channel.invokeMethod('playBytes', bytes);
}
Would it be true to say that, thanks to the null-safety feature of Dart, we are not responsible in the event that the 'bytes' parameter is passed in as null by the plugin user (and thus causing a runtime crash) because in order to do so, they would have to explicitly unwrap a nullable variable, thereby promising that it is is not null.
OR... is there some other thing we should do such as throwing an exception?
With sound null safety, there is no way to call that method with null as argument.
With unsound null safety, which is what you get if not every library of your program is opted into null safety, it's technically possible to pass null as an argument (because a non-null safe library could be doing the calling, or could be passing null into other null safe code, which doesn't check because it assumes null safety.)
You can choose to check the value coming in, as an extra precaution.
The language makes that hard for you, because locally the code looks null safe.
Something like
if (bytes as dynamic == null) throw ArgumentError.notNull("bytes");
I personally wouldn't bother with that, unless there is a real risk of something going spectacularly wrong if null manages to get into the code.
It's documented as not allowing a null value, and most well-behaved code will respect that. Eventually, when all programs are soundly null safe, that check would just be dead code.
First:
if you mean the final user that use app on device, you should have a validation for input.
Second:
if you mean someone try your plugin to code the app.
you can add required keyword, the dart analysis give the user the error if don't pass bytes.
static Future<void> startPlaying({required Uint8List bytes}) async {
_channel.invokeMethod('playBytes', bytes);
}
Related
As far as I know, the benefit of null safety is to prevent the accidental assignment of null to a variable and then later doing something like nullable_variable.foo() which would cause a runtime error.
But even when I am not using null safety, I do get a compilation error when calling a method on an object that have the null value, for example I get a compilation error when doing the following:
class Student
{
void foo()
{
}
}
void main()
{
Student? s1 = null; // not using null safety here
s1.foo(); // this causes a compilation error
}
So what I mean is that I am still getting the benefit of null safety without using null safety, so what is the point of null safety?!
You are using "Null Safety". The Null Safety feature is what allows you to write Student? to begin with, to distinguish between types which allow null and types which do not.
With that knowledge, the compiler can disallow calling methods on a nullable type that are not also allowed on null. And it does.
You get a compile-time error for something that, without Null Safety, you'd have written Student s1 = null;, had that accepted by the compiler, and gotten a runtime error.
The promise of Null Safety is that you get compile-time errors instead of runtime errors. The cost is that you need to check for null (or do unsafe casts to non-null types, but checking is better), and you have to explicitly include null in types where you do want to accept null.
To say in simple terms using your above example
Student s1 = null is valid without null safety which will lead to various other problems , Especially when you are dealing with the huge project.
So when you opt into null safety, types in your code are non-nullable by default, meaning that variables can’t contain null unless you say they can.
With null safety, your runtime null-dereference errors turn into edit-time analysis errors.
Where as in null safety , you can't have somethin like Student s1 = null,
Instead use Student? s1 = null. Meaning you are explicity saying the compiler that you are aware that this value can be null and take care of it in the entire program.
So flutter accepts that and helps you through by giving features like ! ?? ?.
To summarize , the null safety was introduced because,
Developers like statically-typed languages like Dart because they enable the type checker to find mistakes in code at compile time, usually right in the IDE. The sooner you find a bug, the sooner you can fix it. When language designers talk about “fixing null reference errors”, they mean enriching the static type checker so that the language can detect mistakes
And Dart is designed to run on an end-user’s device. If a server application fails, you can often restart it before anyone notices. But when a Flutter app crashes on a user’s phone, they are not happy. When your users aren’t happy, you aren’t happy.
Please follow the below links to dive deep into the null-safety concept.
https://dart.dev/null-safety
https://dart.dev/null-safety/understanding-null-safety
I'm using an IO Library which returns a Future<String>. While, yes, the returned type is String instead of String?, the documentation of that library method clearly states that null will be returned if the operation fails (Instead of throwing an exception). Therefore, I need to check for null myself and handle the exception throwing myself.
However, if I check the return value for null, Dart tells me that the operand can't be null and I therefore shouldn't be checking for it.
What should be done in such a case?
As is discussed in the comments, this issue can be seen when using legacy code that hasn't been updated for Dart 2.12 with null-safety.
In previous versions of Dart (pre-2.12), types did not have to have a trailing ? symbol to signify that a value may be null. A Future<String>, for example, could easily complete with a value of null.
To avoid this, make sure all your dependencies are null-safe.
Is there a better way to do this?
Assignment(
dueAt: json['due_at'] == null ?
null :
DateTime.parse(json['due_at']).toLocal()
)
The attribute "dueAt" in Assignment class can be null and i need to parse the string of json['due_at'] to a DateTime, but json['due_at'] can be null too.
Is not really a problem right now but seems noisy and repetitive.
First and foremost, it looks like you're writing JSON serialization code by hand. Your life will be much easier and less bug-prone if you let a library do this instead. json_serializable is very simple and powerful and 100% worth looking into.
However, this pattern is still common outside of json code.
You could also consider writing an extension method for Object? that behaves like the Kotlin standard library's let function (https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/let.html)
You can then use Dart's ?. syntax to handle the rest of the logic:
// extension on T rather than Object? to maintain type information
extension Example<T> on T {
R let<R>(R Function(T) function) => function(this);
}
This just applies a given function to this, which isn't incredibly useful on it's own, but allows the use of ?.:
final DateTime? dueAt = json['due_at']?.let(DateTime.parse);
If json['due_at'] evaluates to null, the ?. operator short-circuits, and dueAt is set to null. Otherwise, it evaluates to DateTime.parse(json['due_at']).
Or, you could just use package:kt_dart which ports much of the Kotlin standard library to Dart
In this particular case you may want to use tryParse instead of parse. If dueAt is of type DateTime? you can simply call:
Assignment( dueAt: DateTime.tryParse(json['due_at'])?.toLocal() );
Be aware though that tryParse will return null for any invalid date string (be it null or an improperly formatted string). This may or may not be desired behavior depending on your intended use.
I've recently upgraded Dart (using v2.12.4) and trying to migrate an app I've made.
I'm now stuck at an issue that I can't seem to resolve.
Consider the following pseudo-code:
class Notifications {
Future<List<NotificationItem>> notificationItems;
fillNotificationList() async {
notificationItems = await httpService.getFromEndpoint();
}
}
The notificationItems currently errors with Non-nullable instance field 'notifications' must be initialized..
I've tried different solutions; adding late keyword makes the application throw a LateInitializationError exception and appending = [] gives a type error.
How can I successfully have a Future variable with the null safety features in recent versions of Dart?
It seems to be a nullable variable. Meaning there is a point in time in your program where this is clearly null. So declare it as such:
Future<List<NotificationItem>>? notificationItems;
The rest of your code seems a little weird to me. You named a future like I would name the actual result. You have an async method that doesn't do any async work. Maybe that's just because the example here is simplified.
Or maybe you really really want to insist this is never null. You could initialize it with a completed Future with an empty list:
Future<List<NotificationItem>>? notificationItems = Future.value(<NotificationItem>[]);
I want to add two extension functions to ResultSet that gets a value as a LocalDate.
fun ResultSet.getLocalDate(colName: String) = getDate(colName)?.toLocalDate()
fun ResultSet.getLocalDate(colIndex: Int) = getDate(colIndex)?.toLocalDate()
The problem is getDate() returns a Date!, and obviously I could get a null error without the ?. call before toLocalDate(). But then anyone using this extension must use the result as a LocalDate? rather than a LocalDate!.
Is there any way I can maintain the platform type for consistency's sake? And let the user of the extension function decide if it is allowed to be nullable or not? Or am I looking at this wrongly as an inconvenience rather than a feature?
Look at it from a different angle: if you could make your functions return a value of platform type LocalDate!, Java unsafe nullability would spread to the functions usages in your Kotlin code: they would return null at any time, possibly unexpected to the caller using the return value as non-null.
Kotlin, in turn, is null-safe and it won't allow passing null silently to somewhere where it will cause an NPE. Instead, every value is either passed around as nullable or passes non-null check or assertion.
Platform types are non-denotable in the language, this is just a way of dealing with unsafe Java nullability (simply treating all Java values as nullable wouldn't work). They provide you a way to state that you believe that this call to Java code won't return null: when you treat T! as T, an assertion is generated to check it. Otherwise you work with platform type T! as with nullable T?.
Null safety is one of the key points in Kotlin language design, and it makes you decide for each value in your Kotlin code whether it is nullable or not.
You have two options for API design:
Return a non-null value, checking the nullability inside your function
Return nullable value and thus warn the caller about possible null
However, if a function has semantics allowing the caller to assume that it won't return null in some conditions, you can make a wrapper function that makes the assertion. This is feasible if coupled with additional logic or fallback, otherwise it will hardly be more concise than the assertion (!!) at call site.