Null safety is the largest change we’ve made to Dart since we replaced the original unsound optional type system with a sound static type system in Dart 2.0. When Dart first launched, compile-time null safety was a rare feature needing a long introduction. Today, Kotlin, Swift, Rust, and other languages all have their own answers to what has become a very familiar problem. Here is an example: Show
If you run this Dart program without null safety, it throws a 4 exception on the call to 5. The 6 value is an instance of the 7 class, and 7 has no “length” getter. Runtime failures suck. This is especially true in a language like Dart that 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.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 like the above attempt to call 5 on a value that might be 6.There is no one true solution to this problem. Rust and Kotlin both have their own approach that makes sense in the context of those languages. This doc walks through all the details of our answer for Dart. It includes changes to the static type system and a suite of other modifications and new language features to let you not only write null-safe code but hopefully to enjoy doing so. This document is long. If you want something shorter that covers just what you need to know to get up and running, start with the overview. When you are ready for a deeper understanding and have the time, come back here so you can understand how the language handles 6, why we designed it that way, and how to write idiomatic, modern, null-safe Dart. (Spoiler alert: it ends up surprisingly close to how you write Dart today.)The various ways a language can tackle null reference errors each have their pros and cons. These principles guided the choices we made:
Note that eliminating 6 is not a goal. There’s nothing wrong with 6. On the contrary, it’s really useful to be able to represent the absence of a value. Building support for a special “absent” value directly into the language makes working with absence flexible and usable. It underpins optional parameters, the handy 9 null-aware operator, and default initialization. It is not 6 that is bad, it is having 6 go where you don’t expect it that causes problems.Thus with null safety, our goal is to give you control and insight into where 6 can flow through your program and certainty that it can’t flow somewhere that would cause a crash.Nullability in the type systemNull safety begins in the static type system because everything else rests upon that. Your Dart program has a whole universe of types in it: primitive types like 3 and 4, collection types like 5, and all of the classes and types you and the packages you use define. Before null safety, the static type system allowed the value 6 to flow into expressions of any of those types.In type theory lingo, the 7 type was treated as a subtype of all types:The set of operations—getters, setters, methods, and operators—allowed on some expressions are defined by its type. If the type is 5, you can call 9 or 0 on it. If it’s 3, you can call 2. But the 6 value doesn’t define any of those methods. Allowing 6 to flow into an expression of some other type means any of those operations can fail. This is really the crux of null reference errors—every failure comes from trying to look up a method or property on 6 that it doesn’t have.Non-nullable and nullable typesNull safety eliminates that problem at the root by changing the type hierarchy. The 7 type still exists, but it’s no longer a subtype of all types. Instead, the type hierarchy looks like this:Since 7 is no longer a subtype, no type except the special 7 class permits the value 6. We’ve made all types non-nullable by default. If you have a variable of type 4, it will always contain a string. There, we’ve fixed all null reference errors.If we didn’t think 6 was useful at all, we could stop here. But 6 is useful, so we still need a way to handle it. Optional parameters are a good illustrative case. Consider this null safe Dart code:
Here, we want to allow the 3 parameter to accept any string, or the value 6, but nothing else. To express that, we give 3 a nullable type by slapping 6 at the end of the underlying base type 4. Under the hood, this is essentially defining a union of the underlying type and the 7 type. So 9 would be a shorthand for 00 if Dart had full-featured union types.Using nullable typesIf you have an expression with a nullable type, what can you do with the result? Since our principle is safe by default, the answer is not much. We can’t let you call methods of the underlying type on it because those might fail if the value is 6:
This would crash if we let you run it. The only methods and properties we can safely let you access are ones defined by both the underlying type and the 7 class. That’s just 03, 04, and 05. So you can use nullable types as map keys, store them in sets, compare them to other values, and use them in string interpolation, but that’s about it.How do they interact with non-nullable types? It’s always safe to pass a non-nullable type to something expecting a nullable type. If a function accepts 9 then passing a 4 is allowed because it won’t cause any problems. We model this by making every nullable type a supertype of its underlying type. You can also safely pass 6 to something expecting a nullable type, so 7 is also a subtype of every nullable type:But going the other direction and passing a nullable type to something expecting the underlying non-nullable type is unsafe. Code that expects a 4 may call 4 methods on the value. If you pass a 9 to it, 6 could flow in and that could fail:
This program is not safe and we shouldn’t allow it. However, Dart has always had this thing called implicit downcasts. If you, for example, pass a value of type 14 to a function expecting an 4, the type checker allows it:
To maintain soundness, the compiler silently inserts an 16 cast on the argument to 17. That cast could fail and throw an exception at runtime, but at compile time, Dart says this is OK. Since non-nullable types are modeled as subtypes of nullable types, implicit downcasts would let you pass a 9 to something expecting a 4. Allowing that would violate our goal of being safe by default. So with null safety we are removing implicit downcasts entirely.This makes the call to 20 produce a compile error, which is what you want. But it also means all implicit downcasts become compile errors, including the call to 17. You’ll have to add the explicit downcast yourself:
We think this is an overall good change. Our impression is that most users never liked implicit downcasts. In particular, you may have been burned by this before:
Spot the bug? The 22 method is lazy, so it returns an 23, not a 5. This program compiles but then throws an exception at runtime when it tries to cast that 23 to the 5 type that 27 declares it returns. With the removal of implicit downcasts, this becomes a compile error.Where were we? Right, OK, so it’s as if we’ve taken the universe of types in your program and split them into two halves: There is a region of non-nullable types. Those types let you access all of the interesting methods, but can never ever contain 6. And then there is a parallel family of all of the corresponding nullable types. Those permit 6, but you can’t do much with them. We let values flow from the non-nullable side to the nullable side because doing so is safe, but not the other direction.That seems like nullable types are basically useless. They have no methods and you can’t get away from them. Don’t worry, we have a whole suite of features to help you move values from the nullable half over to the other side that we will get to soon. Top and bottomThis section is a little esoteric. You can mostly skip it, except for two bullets at the very end, unless you’re into type system stuff. Imagine all the types in your program with edges between ones that are subtypes and supertypes of each other. If you were to draw it, like the diagrams in this doc, it would form a huge directed graph with supertypes like 14 near the top and leaf classes like your own types near the bottom.If that directed graph comes to a point at the top where there is a single type that is the supertype (directly or indirectly), that type is called the top type. Likewise, if there is a weird type at that bottom that is a subtype of every type, you have a bottom type. (In this case, your directed graph is a lattice.) It’s convenient if your type system has a top and bottom type, because it means that type-level operations like least upper bound (which type inference uses to figure out the type of a conditional expression based on the types of its two branches) can always produce a type. Before null safety, 14 was Dart’s top type and 7 was its bottom type.Since 14 is non-nullable now, it is no longer a top type. 7 is not a subtype of it. Dart has no named top type. If you need a top type, you want 35. Likewise, 7 is no longer the bottom type. If it was, everything would still be nullable. Instead, we’ve added a new bottom type named 37:In practice, this means:
Ensuring correctnessWe divided the universe of types into nullable and non-nullable halves. In order to maintain soundness and our principle that you can never get a null reference error at runtime unless you ask for it, we need to guarantee that 6 never appears in any type on the non-nullable side.Getting rid of implicit downcasts and removing 7 as a bottom type covers all of the main places that types flow through a program across assignments and from arguments into parameters on function calls. The main remaining places where 6 can sneak in are when a variable first comes into being and when you leave a function. So there are some additional compile errors:Invalid returnsIf a function has a non-nullable return type, then every path through the function must reach a 47 statement that returns a value. Before null safety, Dart was pretty lax about missing returns. For example:
If you analyzed this, you got a gentle hint that maybe you forgot a return, but if not, no big deal. That’s because if execution reaches the end of a function body then Dart implicitly returns 6. Since every type is nullable, technically this function is safe, even though it’s probably not what you want.With sound non-nullable types, this program is flat out wrong and unsafe. Under null safety, you get a compile error if a function with a non-nullable return type doesn’t reliably return a value. By “reliably”, I mean that the language analyzes all of the control flow paths through the function. As long as they all return something, it is satisfied. The analysis is pretty smart, so even this function is OK:
We’ll dive more deeply into the new flow analysis in the next section. Uninitialized variablesWhen you declare a variable, if you don’t give it an explicit initializer, Dart default initializes the variable with 6. That’s convenient, but obviously totally unsafe if the variable’s type is non-nullable. So we have to tighten things up for non-nullable variables:
These restrictions sound onerous, but they aren’t too bad in practice. They are very similar to the existing restrictions around 52 variables and you’ve likely been working with those for years without even really noticing. Also, remember that these only apply to non-nullable variables. You can always make the type nullable and then get the default initialization to 6.Even so, the rules do cause friction. Fortunately, we have a suite of new language features to lubricate the most common patterns where these new limitations slow you down. First, though, it’s time to talk about flow analysis. Flow analysisControl flow analysis has been around in compilers for years. It’s mostly hidden from users and used during compiler optimization, but some newer languages have started to use the same techniques for visible language features. Dart already has a dash of flow analysis in the form of type promotion: 2Note how on the marked line, we can call 54 on 55. That method is defined on 5, not 14. This works because the type checker looks at all of the 58 expressions and the control flow paths in the program. If the body of some control flow construct only executes when a certain 58 expression on a variable is true, then inside that body the variable’s type is “promoted” to the tested type.In the example here, the then branch of the 60 statement only runs when 55 actually contains a list. Therefore, Dart promotes 55 to type 5 instead of its declared type 14. This is a handy feature, but it’s pretty limited. Prior to null safety, the following functionally identical program did not work: 3Again, you can only reach the 65 call when 55 contains a list, so this program is dynamically correct. But the type promotion rules were not smart enough to see that the 47 statement means the second statement can only be reached when 55 is a list.For null safety, we’ve taken this limited analysis and made it much more powerful in several ways. Reachability analysisFirst off, we fixed the long-standing complaint that type promotion isn’t smart about early returns and other unreachable code paths. When analyzing a function, it now takes into account 47, 70, 71, and any other way execution might terminate early in a function. Under null safety, this function: 4Is now perfectly valid. Since the 60 statement will exit the function when 55 is not a 5, Dart promotes 55 to be 5 on the second statement. This is a really nice improvement that helps a lot of Dart code, even stuff not related to nullability.Never for unreachable codeYou can also program this reachability analysis. The new bottom type 37 has no values. (What kind of value is simultaneously a 4, 79, and 3?) So what does it mean for an expression to have type 37? It means that expression can never successfully finish evaluating. It must throw an exception, abort, or otherwise ensure that the surrounding code expecting the result of the expression never runs.In fact, according to the language, the static type of a 71 expression is 37. The type 37 is declared in the core libraries and you can use it as a type annotation. Maybe you have a helper function to make it easier to throw a certain kind of exception: 5You might use it like so: 6This program analyzes without error. Notice that the last line of the 04 method accesses 86 and 87 on 88. It has been promoted to 89 even though the function doesn’t have any 47 or 71. The control flow analysis knows that the declared type of 92 is 37 which means the then branch of the 60 statement must abort somehow. Since the second statement can only be reached when 88 is a 89, Dart promotes it.In other words, using 37 in your own APIs lets you extend Dart’s reachability analysis.Definite assignment analysisI mentioned this one briefly with local variables. Dart needs to ensure a non-nullable local variable is always initialized before it is read. We use definite assignment analysis to be as flexible about that as possible. The language analyzes each function body and tracks the assignments to local variables and parameters through all control flow paths. As long as the variable is assigned on every path that reaches some use of a variable, the variable is considered initialized. This lets you declare a variable with no initializer and then initialize it afterwards using complex control flow, even when the variable has a non-nullable type. We also use definite assignment analysis to make final variables more flexible. Before null safety, it can be difficult to use 52 for local variables if you need to initialize them in any sort of interesting way: 7This would be an error since the 99 variable is 52 but has no initializer. With the smarter flow analysis under null safety, this program is fine. The analysis can tell that 99 is definitely initialized exactly once on every control flow path, so the constraints for marking a variable 52 are satisfied.Type promotion on null checksThe smarter flow analysis helps lots of Dart code, even code not related to nullability. But it’s not a coincidence that we’re making these changes now. We have partitioned types into nullable and non-nullable sets. If you have a value of a nullable type, you can’t really do anything useful with it. In cases where the value is 6, that restriction is good. It’s preventing you from crashing.But if the value isn’t 6, it would be good to be able to move it over to the non-nullable side so you can call methods on it. Flow analysis is one of the primary ways to do this for local variables and parameters. We’ve extended type promotion to also look at 05 and 06 expressions.If you check a local variable with nullable type to see if it is not 6, Dart then promotes the variable to the underlying non-nullable type: 8Here, 08 has a nullable type. Normally, that prohibits you from calling 09 on it. But because we have guarded that call in an 60 statement that checks to ensure the value is not 6, Dart promotes it from 12 to 13 and lets you call methods on it or pass it to functions that expect non-nullable lists.This sounds like a fairly minor thing, but this flow-based promotion on null checks is what makes most existing Dart code work under null safety. Most Dart code is dynamically correct and does avoid throwing null reference errors by checking for 6 before calling methods. The new flow analysis on null checks turns that dynamic correctness into provable static correctness.It also, of course, works with the smarter analysis we do for reachability. The above function can be written just as well as: 9The language is also smarter about what kinds of expressions cause promotion. An explicit 05 or 06 of course works. But explicit casts using 17, or assignments, or the postfix 18 operator we’ll get to soon also cause promotion. The general goal is that if the code is dynamically correct and it’s reasonable to figure that out statically, the analysis should be clever enough to do so.Note that type promotion only works on local variables, not on fields or top-level variables. For more information about working with non-local variables, see . Unnecessary code warningsHaving smarter reachability analysis and knowing where 6 can flow through your program helps ensure that you add code to handle 6. But we can also use that same analysis to detect code that you don’t need. Before null safety, if you wrote something like: 0Dart had no way of knowing if that null-aware 9 operator is useful or not. For all it knows, you could pass 6 to the function. But in null safe Dart, if you have annotated that function with the now non-nullable 5 type, then it knows 24 will never be 6. That implies the 9 will never do anything useful and you can and should just use 27.To help you simplify your code, we’ve added warnings for unnecessary code like this now that the static analysis is precise enough to detect it. Using a null-aware operator or even a check like 05 or 06 on a non-nullable type gets reported as a warning.And, of course, this plays with non-nullable type promotion too. Once a variable has been promoted to a non-nullable type, you get a warning if you redundantly check it again for 6: 1You get a warning on the 9 here because at the point that it executes, we already know 24 cannot be 6. The goal with these warnings is not just to clean up pointless code. By removing unneeded checks for 6, we ensure that the remaining meaningful checks stand out. We want you to be able to look at your code and see where 6 can flow.Working with nullable typesWe’ve now corralled 6 into the set of nullable types. With flow analysis, we can safely let some non- 6 values hop over the fence to the non-nullable side where we can use them. That’s a big step, but if we stop here, the resulting system is still painfully restrictive. Flow analysis only helps with locals and parameters.To try to regain as much of the flexibility that Dart had before null safety—and to go beyond it on some places—we have a handful of other new features. Smarter null-aware methodsDart’s null aware operator 9 is much older than null safety. The runtime semantics state that if the receiver is 6 then the property access on the right-hand side is skipped and the expression evaluates to 6: 2Instead of throwing an exception, this prints “null”. The null-aware operator is a nice tool for making nullable types usable in Dart. While we can’t let you call methods on nullable types, we can and do let you use null-aware operators on them. The post-null safety version of the program is: 3It works just like the previous one. However, if you’ve ever used null-aware operators in Dart, you’ve probably encountered an annoyance when using them in method chains. Let’s say you want to see if the length of a potentially absent string is an even number (not a particularly realistic problem, I know, but work with me here): 4Even though this program uses 9, it still throws an exception at runtime. The problem is that the receiver of the 42 expression is the result of the entire 43 expression to its left. That expression evaluates to 6, so we get a null reference error trying to call 42. If you’ve ever used 9 in Dart, you probably learned the hard way that you have to apply the null-aware operator to every property or method in a chain after you use it once: 5This is annoying, but, worse, it obscures important information. Consider: 6Here’s a question for you: Can the 47 getter on 48 return 6? It looks like it could because you’re using 9 on the result. But it may just be that the second 9 is only there to handle cases where 52 is 6, not the result of 47. You can’t tell.To address this, we borrowed a smart idea from C#’s design of the same feature. When you use a null-aware operator in a method chain, if the receiver evaluates to 6, then the entire rest of the method chain is short-circuited and skipped. This means if 47 has a non-nullable return type, then you can and should write: 7In fact, you’ll get an unnecessary code warning on the second 9 if you don’t. If you see code like: 6Then you know for certain it means that 47 itself has a nullable return type. Each 9 corresponds to a unique path that can cause 6 to flow into the method chain. This makes null-aware operators in method chains both more terse and more precise.While we were at it, we added a couple of other null-aware operators: 9There isn’t a null-aware function call operator, but you can write: 0Null assertion operatorThe great thing about using flow analysis to move a nullable variable to the non-nullable side of the world is that doing so is provably safe. You get to call methods on the previously-nullable variable without giving up any of the safety or performance of non-nullable types. But many valid uses of nullable types can’t be proven to be safe in a way that pleases static analysis. For example: 1If you try to run this, you get a compile error on the call to 61. The 62 field is nullable because it won’t have a value in a successful response. We can see by inspecting the class that we never access the 62 message when it is 6. But that requires understanding the relationship between the value of 65 and the nullability of 62. The type checker can’t see that connection.In other words, we human maintainers of the code know that error won’t be 6 at the point that we use it and we need a way to assert that. Normally, you assert types using an 17 cast, and you can do the same thing here: 2Casting 62 to the non-nullable 4 type will throw a runtime exception if the cast fails. Otherwise, it gives us a non-nullable string that we can then call methods on.“Casting away nullability” comes up often enough that we have a new shorthand syntax. A postfix exclamation mark ( 18) takes the expression on the left and casts it to its underlying non-nullable type. So the above function is equivalent to: 3This one-character “bang operator” is particularly handy when the underlying type is verbose. It would be really annoying to have to write 72 just to cast away a single 6 from some type.Of course, like any cast, using 18 comes with a loss of static safety. The cast must be checked at runtime to preserve soundness and it may fail and throw an exception. But you have control over where these casts are inserted, and you can always see them by looking through your code.Late variablesThe most common place where the type checker cannot prove the safety of code is around top-level variables and fields. Here is an example: 4Here, the 75 method is called before 76. That means 77 will be initialized to a non-null value before it is used. But it’s not feasible for a static analysis to determine that. (It might be possible for a trivial example like this one, but the general case of trying to track the state of each instance of a class is intractable.)Because the type checker can’t analyze uses of fields and top-level variables, it has a conservative rule that non-nullable fields have to be initialized either at their declaration (or in the constructor initialization list for instance fields). So Dart reports a compile error on this class. You can fix the error by making the field nullable and then using null assertion operators on the uses: 5This works fine. But it sends a confusing signal to the maintainer of the class. By marking 77 nullable, you imply that 6 is a useful, meaningful value for that field. But that’s not the intent. The 77 field should never be observed in its 6 state.To handle the common pattern of state with delayed initialization, we’ve added a new modifier, 82. You can use it like this: 6Note that the 77 field has a non-nullable type, but is not initialized. Also, there’s no explicit null assertion when it’s used. There are a few models you can apply to the semantics of 82, but I think of it like this: The 82 modifier means “enforce this variable’s constraints at runtime instead of at compile time”. It’s almost like the word “late” describes when it enforces the variable’s guarantees.In this case, since the field is not definitely initialized, every time the field is read, a runtime check is inserted to make sure it has been assigned a value. If it hasn’t, an exception is thrown. Giving the variable the type 4 means “you should never see me with a value other than a string” and the 82 modifier means “verify that at runtime”.In some ways, the 82 modifier is more “magical” than using 6 because any use of the field could fail, and there isn’t anything textually visible at the use site. But you do have to write 82 at the declaration to get this behavior, and our belief is that seeing the modifier there is explicit enough for this to be maintainable.In return, you get better static safety than using a nullable type. Because the field’s type is non-nullable now, it is a compile error to try to assign 6 or a nullable 4 to the field. The 82 modifier lets you defer initialization, but still prohibits you from treating it like a nullable variable.Lazy initializationThe 82 modifier has some other special powers too. It may seem paradoxical, but you can use 82 on a field that has an initializer: 7When you do this, the initializer becomes lazy. Instead of running it as soon as the instance is constructed, it is deferred and run lazily the first time the field is accessed. In other words, it works exactly like an initializer on a top-level variable or static field. This can be handy when the initialization expression is costly and may not be needed. Running the initializer lazily gives you an extra bonus when you use 82 on an instance field. Usually instance field initializers cannot access 97 because you don’t have access to the new object until all field initializers have completed. But with a 82 field, that’s no longer true, so you can access 97, call methods, or access fields on the instance.Late final variablesYou can also combine 82 with 52: 8Unlike normal 52 fields, you do not have to initialize the field in its declaration or in the constructor initialization list. You can assign to it later at runtime. But you can only assign to it once, and that fact is checked at runtime. If you try to assign to it more than once—like calling both 75 and 04 here—the second assignment throws an exception. This is a great way to model state that gets initialized eventually and is immutable afterwards.In other words, the new 82 modifier in combination with Dart’s other variable modifiers covers most of the feature space of 06 in Kotlin and 07 in Swift. You can even use it on local variables if you want a little local lazy evaluation.Required named parametersTo guarantee that you never see a 6 parameter with a non-nullable type, the type checker requires all optional parameters to either have a nullable type or a default value. What if you want to have a named parameter with a non-nullable type and no default value? That would imply that you want to require the caller to always pass it. In other words, you want a parameter that is named but not optional.I visualize the various kinds of Dart parameters with this table: 9For unclear reasons, Dart has long supported three corners of this table but left the combination of named+mandatory empty. With null safety, we filled that in. You declare a required named parameter by placing 09 before the parameter: 0Here, all the parameters must be passed by name. The parameters 10 and 11 are optional and can be omitted. The parameters 12 and 13 are required and must be passed. Note that required-ness is independent of nullability. You can have required named parameters of nullable types, and optional named parameters of non-nullable types (if they have a default value).This is another one of those features that I think makes Dart better regardless of null safety. It simply makes the language feel more complete to me. Abstract fieldsOne of the neat features of Dart is that it upholds a thing called the uniform access principle. In human terms it means that fields are indistinguishable from getters and setters. It’s an implementation detail whether a “property” in some Dart class is computed or stored. Because of this, when defining an interface using an abstract class, it’s typical to use a field declaration: 1The intent is that users only implement that class and don’t extend it. The field syntax is simply a shorter way of writing a getter/setter pair: 2But Dart doesn’t know that this class will never be used as a concrete type. It sees that 14 declaration as a real field. And, unfortunately, that field is non-nullable and has no initializer, so you get a compile error.One fix is to use explicit abstract getter/setter declarations like in the second example. But that’s a little verbose, so with null safety we also added support for explicit abstract field declarations: 3This behaves exactly like the second example. It simply declares an abstract getter and setter with the given name and type. Working with nullable fieldsThese new features cover many common patterns and make working with 6 pretty painless most of the time. But even so, our experience is that nullable fields can still be difficult. In cases where you can make the field 82 and non-nullable, you’re golden. But in many cases you need to check to see if the field has a value, and that requires making it nullable so you can observe the 6.You might expect this to work: 4Inside 18, we check to see if 77 is 6. If not, we access it and end up calling 2 on it. Unfortunately, this is not allowed. Flow-based type promotion does not apply to fields because the static analysis cannot prove that the field’s value doesn’t change between the point that you check for 6 and the point that you use it. (Consider that in pathological cases, the field itself could be overridden by a getter in a subclass that returns 6 the second time it is called.)So, since we care about soundness, fields don’t promote and the above method does not compile. This is annoying. In simple cases like here, your best bet is to slap a 18 on the use of the field. It seems redundant, but that’s more or less how Dart behaves today.Another pattern that helps is to copy the field to a local variable first and then use that instead: 5Since the type promotion does apply to locals, this now works fine. If you need to change the value, just remember to store back to the field and not just the local. For more information on handling these and other type promotion issues, see Fixing type promotion failures. Nullability and genericsLike most modern statically-typed languages, Dart has generic classes and generic methods. They interact with nullability in a few ways that seem counter-intuitive but make sense once you think through the implications. First is that “is this type nullable?” is no longer a simple yes or no question. Consider: 6In the definition of 25, is 26 a nullable type or a non-nullable type? As you can see, it can be instantiated with either kind. The answer is that 26 is a potentially nullable type. Inside the body of a generic class or method, a potentially nullable type has all of the restrictions of both nullable types and non-nullable types.The former means you can’t call any methods on it except the handful defined on Object. The latter means that you must initialize any fields or variables of that type before they’re used. This can make type parameters pretty hard to work with. In practice, a few patterns show up. In collection-like classes where the type parameter can be instantiated with any type at all, you just have to deal with the restrictions. In most cases, like the example here, it means ensuring you do have access to a value of the type argument’s type whenever you need to work with one. Fortunately, collection-like classes rarely call methods on their elements. In places where you don’t have access to a value, you can make the use of the type parameter nullable: 7Note the 6 on the declaration of 55. Now the field has an explicitly nullable type, so it is fine to leave it uninitialized.When you make a type parameter type nullable like 30 here, you may need to cast the nullability away. The correct way to do that is using an explicit 31 cast, not the 18 operator: 8The 18 operator always throws if the value is 6. But if the type parameter has been instantiated with a nullable type, then 6 is a perfectly valid value for 26: 9This program should run without error. Using 31 accomplishes that. Using 18 would throw an exception.Other generic types have some bound that restricts the kinds of type arguments that can be applied: 0If the bound is non-nullable, then the type parameter is also non-nullable. This means you have the restrictions of non-nullable types—you can’t leave fields and variables uninitialized. The example class here must have a constructor that initializes the fields. In return for that restriction, you can call any methods on values of the type parameter type that are declared on its bound. Having a non-nullable bound does, however, prevent users of your generic class from instantiating it with a nullable type argument. That’s probably a reasonable limitation for most classes. You can also use a nullable bound: 1This means that in the body of the class you get the flexibility of treating the type parameter as nullable, but you also have the limitations of nullability. You can’t call anything on a variable of that type unless you deal with the nullability first. In the example here, we copy the fields in local variables and check those locals for 6 so that flow analysis promotes them to non-nullable types before we use 40.Note that a nullable bound does not prevent users from instantiating the class with non-nullable types. A nullable bound means that the type argument can be nullable, not that it must. (In fact, the default bound on type parameters if you don’t write an 41 clause is the nullable bound 35.) There is no way to require a nullable type argument. If you want uses of the type parameter to reliably be nullable and be implicitly initialized to 6, you can use 30 inside the body of the class.Core library changesThere are a couple of other tweaks here and there in the language, but they are minor. Things like the default type of a 45 with no 46 clause is now 14 instead of 48. Fallthrough analysis in switch statements uses the new flow analysis.The remaining changes that really matter to you are in the core libraries. Before we embarked on the Grand Null Safety Adventure, we worried that it would turn out there was no way to make our core libraries null safe without massively breaking the world. It turned out not so dire. There are a few significant changes, but for the most part, the migration went smoothly. Most core libraries either did not accept 6 and naturally move to non-nullable types, or do and gracefully accept it with a nullable type.There are a few important corners, though: The Map index operator is nullableThis isn’t really a change, but more a thing to know. The index 0 operator on the Map class returns 6 if the key isn’t present. This implies that the return type of that operator must be nullable: 52 instead of 53.We could have changed that method to throw an exception when the key isn’t present and then given it an easier-to-use non-nullable return type. But code that uses the index operator and checks for 6 to see if the key is absent is very common, around half of all uses based on our analysis. Breaking all of that code would have set the Dart ecosystem aflame.Instead, the runtime behavior is the same and thus the return type is obliged to be nullable. This means you generally cannot immediately use the result of a map lookup: 2This gives you a compile error on the attempt to call 5 on a nullable string. In cases where you know the key is present you can teach the type checker by using 18: 3We considered adding another method to Map that would do this for you: look up the key, throw if not found, or return a non-nullable value otherwise. But what to call it? No name would be shorter than the single-character 18, and no method name would be clearer than seeing a 18 with its built-in semantics right there at the call site. So the idiomatic way to access a known-present element in a map is to use 59. You get used to it.No unnamed List constructorThe unnamed constructor on 5 creates a new list with the given size but does not initialize any of the elements. This would poke a very large hole in the soundness guarantees if you created a list of a non-nullable type and then accessed an element.To avoid that, we have removed the constructor entirely. It is an error to call 61 in null safe code, even with a nullable type. That sounds scary, but in practice most code creates lists using list literals, 62, 63, or as a result of transforming some other collection. For the edge case where you want to create an empty list of some type, we added a new 64 constructor.The pattern of creating a completely uninitialized list has always felt out of place in Dart, and now it is even more so. If you have code broken by this, you can always fix it by using one of the many other ways to produce a list. Cannot set a larger length on non-nullable listsThis is little known, but the 65 getter on 5 also has a corresponding setter. You can set the length to a shorter value to truncate the list. And you can also set it to a longer length to pad the list with uninitialized elements.If you were to do that with a list of a non-nullable type, you’d violate soundness when you later accessed those unwritten elements. To prevent that, the 65 setter will throw a runtime exception if (and only if) the list has a non-nullable element type and you set it to a longer length. It is still fine to truncate lists of all types, and you can grow lists of nullable types.There is an important consequence of this if you define your own list types that extend 68 or apply 69. Both of those types provide an implementation of 70 that previously made room for the inserted element by setting the length. That would fail with null safety, so instead we changed the implementation of 70 in 69 (which 68 shares) to call 74 instead. Your custom list class should provide a definition of 74 if you want to be able to use that inherited 70 method.Cannot access Iterator.current before or after iterationThe 77 class is the mutable “cursor” class used to traverse the elements of a type that implements 23. You are expected to call 79 before accessing any elements to advance to the first element. When that method returns 80, you have reached the end and there are no more elements.It used to be that 81 returned 6 if you called it either before calling 79 the first time or after iteration finished. With null safety, that would require the return type of 81 to be 85 and not 86. That in turn means every element access would require a runtime 6 check.Those checks would be useless given that almost no one ever accesses the current element in that erroneous way. Instead, we have made the type of 81 be 86. Since there may be a value of that type available before or after iterating, we’ve left the iterator’s behavior undefined if you call it when you aren’t supposed to. Most implementations of 77 throw a 91.SummaryThat is a very detailed tour through all of the language and library changes around null safety. It’s a lot of stuff, but this is a pretty big language change. More importantly, we wanted to get to a point where Dart still feels cohesive and usable. That requires changing not just the type system, but a number of other usability features around it. We didn’t want it to feel like null safety was bolted on. The core points to take away are:
Finally, once you absorb all of that and get your code into the world of null safety, you get a sound program that the compilers can optimize and where every place a runtime error can occur is visible in your code. We hope you feel that’s worth the effort to get there. |