Dart / flutter test setup with null safety - flutter

Update: It was a documentation bug, fixed with: https://github.com/dart-lang/test/pull/1471
According to the docs/examples for the test package (https://pub.dev/packages/test) this test case should work and not trigger warnings. However it does:
The non-nullable local variable 'b' must be assigned before it can be used.
Try giving it an initializer expression, or ensure that it's assigned on every execution path.dart(not_assigned_potentially_non_nullable_local_variable)
Marking the variable as late works, but I want to check that I'm not missing something before I file a bug saying that the docs are wrong. =)
import 'package:test/test.dart';
void main() {
String b;
setUp(() {
b = 'test';
});
group('foo', () {
test('bar', () {
print(b);
});
});
}

You can use late keyword.
ref: https://dart.dev/guides/language/language-tour#late-variables

With Null Safety you have to specifically declare the the variable can be null or you have to initialize it. In this case you may have seen they have also initialized the strings before test. Or You can declare the variable nullable by using
String? b;

Related

Why does it keep saying initialize variable?

Below is the code I wrote. I need to initialize a variable called verificationID for later use. But I keep getting a red squiggly line with the text -
Final variable verificationID must be initialized
Non-nullable instance field vdi must be initialized.
Is this not how you initialize - final [datatype] [name]
I am brand new to flutter and could use any help!
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
enum NumberVerification {
SHOW_MOBILE_FORM_STATE,
SHOW_OTP_FORM_STATE,
}
class LoginScreen extends StatefulWidget {
final String verificationID;
String vdi;
#override
_LoginScreenState createState() => _LoginScreenState();
}
All variables in Dart are getting the value null if nothing else are specified. This is a problem in your case since both verificationID and vdi are specified as non-nullable types (no ? after the type name). So Dart complains about this problem.
Another problem is your final variable which also should be provided a value since this is a read-only variable which can only be assigned a value when initialized.
You therefore need to do:
Change the types to allow null.
Or, provide default value other than null.
Or, make a constructor of your class which gives values to your variables. These values can come from parameters to the constructor.
Because flutter and dart language are null safety. It means you should initialize your variables, and there will be no error regarding this in runtime. So when you write dart codes you must initialize them as follows:
1- In some cases you can init value directly as follows:
final String verificationID = 'value';
2- Or you can get the value from constructor of class.
final String verificationID;
LoginScreen(this.verificationID);
3- And also, you can declare that you will initialize the value later. This way you guarantee that you will initialize the value, so you should use it wisely.
late String verificationID;
verificationID = 'value';
4- Lastly, you may declare a value as nullable. This way, you don't need to initialize the variable directly.
String? verificationID;

Late variable in Dart

I'm new to use Websocket in Flutter.
So I was reading some post (https://blog.logrocket.com/using-websockets-flutter/) to understand how to use websocket, and I have some question.
The guy in this post declare _etheWebsocket,_btcWebsocket variables as late as below.
class CoinbaseProvider {
late final WebSocketChannel _ethWebsocket;
late final WebSocketChannel _btcWebsocket;
CoinbaseProvider()
: _ethWebsocket = WebSocketChannel.connect(
Uri.parse('wss://ws-feed.pro.coinbase.com'),
),
_btcWebsocket = WebSocketChannel.connect(
Uri.parse('wss://ws-feed.pro.coinbase.com'),
);
But why not just declare without late like below??
What is the reason have to declare WebsocketChannel as late.
class CoinbaseProvider {
final WebSocketChannel _ethWebsocket = WebSocketChannel.connect(
Uri.parse('wss://ws-feed.pro.coinbase.com'),
);
final WebSocketChannel _btcWebsocket = WebSocketChannel.connect(
Uri.parse('wss://ws-feed.pro.coinbase.com'),
);
CoinbaseProvider();
Short explanation
You declaration looks better, since in your context you have the values to the variables _ethWebsocket and _btcWebsocket
But why? a dive into late and null-safety features
What's null-safety in Dart? This is a recent released feature (2021) that in summary it prevent us, developers, to create variables of a type that can be implicity null, then avoiding runtime errors as TypeError: can't read property '...' of null
But in summary, unlike before null-safety, now:
All variables can't be null implicity by default!
Show me the code
Before null-safety:
This snippet below is a valid statement before null-safety, this variable can be a String 'hi!' or null
String myVariable; // null by default
After null-safety:
The same snippet now is a invalid statement, the variable should be initialized because her can't be null
String myVariable; // Error!
To declare a variable that can be null by default, as like before the null-safety update you should write as:
String? myVariable; // Note the '?' after the Type
But what if you want to declare variable without the value and without explicitly declaring that it can be null?
The answer is late!
late is just a Dart language feature to allow you say to the compiler: "Hey, I don't have the value of this variable right now, but I promise you I'll set her somewhere else before using it, so her can't be null"
late String myVariable;
print(myVariable); // Throws an LateInitializationError instead of printing 'null'
Conclusion
Given these features and the null-safety use them to avoid wasting time with null pointer exceptions and improve your code typing.
So there's no right or better way, all depends on the context.
For the exact example you used I would say they are identical, and your version would be better. My guess it that they made it like that, is to allow adding additional constructors, maybe like
CoinbaseProvider.customUrl(String eth, String btc)
: _ethWebsocket = WebSocketChannel.connect(
Uri.parse(eth),
),
_btcWebsocket = WebSocketChannel.connect(
Uri.parse(btc),
);

Error to use assignment operators ==? in Dart

I am learning Dart and practicing with this video I came across this way of assigning a value when the variable is null
void main() {
int linus;
linus ??= 100;
print(linus);
}
When trying to test the code in VSCode I get the following error which I cannot identify its origin since from what I understand, I am using what is indicated in the documentation (and the video tutorial).
The non-nullable local variable 'linus' must be assigned before it can be used.
Try giving it an initializer expression, or ensure that it's assigned on every execution path.
The Dart Language now supports a new feature called sound null safety. Variables now are non-nullable by default meaning that you can not assign a null value to a variable unless you explicitly declare they can contain a null.
To indicate that a variable might have the value null, just add ? to its type declaration:
int? linus;
So, remember: every variable must have a value assigned to it before it can be used. As in your example, linus variable is non-nullable by default ,null-aware operator has nothing to do because it will assign value to linus if it is null.So, linus gets no value and thus it can't be used in the print function.
So to solve this, you can do this:
void main() {
int? linus; //marks linus as a variable that can have null value
linus ??= 100;
print(linus);
}
To know more about null safety
The Documentation is Non-Null Safety and you are trying in Null safety version
Please check below code
void main() {
int? linus;
linus ??= 100;
print(linus);
}

Flutter null-safety conditionals in object methods

I'm just working through this whole null-safety mode with my Flutter project and unsure what the difference is with ? and ! in calls to object methods.
For example, the hint was to add a ! conditional. Here's an example I have right now, and I'm unsure if this should be a ? or a ! at the findNbr!.replaceAll().
Future checkItem({String? findNbr}) async {
int? x = int.tryParse(findNbr!.replaceAll('-', ''));
...
Does this mean replaceAll() will not run if findNbr is null?
Or should it be a ? instead? findNbr?.replaceAll()
EDIT: I just noticed I cannot use findNbr?, it's telling String? can't be assigned parameter String.
Or does it mean I say it's not null and run it anyway?
For your information, I have not come close to running my app yet so I have no idea if it even works. But I figure I better know what it's doing before get too much more done. I'm still in the process of converting everything and there's 75-100 dart files. I'm not sure I get the point of it all to be honest, because I just add ? to everything, so its all nullable anyway.
Future checkItem({String? findNbr}) async {
int? x = int.tryParse(findNbr!.replaceAll('-', ''));
...
Does this mean replaceAll() will not run if findNbr is null?
Correct. If findNbr is null, then findNbr! will throw a runtime exception. That would be bad, especially since checkItem's function signature advertises that findNbr is allowed to be null, and therefore it would violate callers' expectations.
Or should it be a ? instead? findNbr?.replaceAll()
EDIT: I just noticed I cannot use findNbr?, it's telling String? can't be assigned parameter String.
You can't use findNbr?.replaceAll(...) because if findNbr is null, then it would be invoking int.tryParse(null), but int.tryParse is not allowed to take a null argument.
What you need to do is one of:
Make findNbr no longer optional:
Future checkItem({required String findNbr}) async {
int? x = int.tryParse(findNbr.replaceAll('-', ''));
...
Allow findNbr to be optional but have a non-null default value:
Future checkItem({String findNbr = ''}) async {
int? x = int.tryParse(findNbr.replaceAll('-', ''));
...
Allow findNbr to be optional but explicitly decide what to do if it is null. For example:
Future checkItem({String? findNbr}) async {
int? x = findNbr == null ? null : int.tryParse(findNbr.replaceAll('-', ''));
...
I'm not sure I get the point of it all to be honest, because I just add ? to everything, so its all nullable anyway.
If you blindly add ? to all types and add ! to all variables, then yes, null-safety would be pointless: doing that would give you the same behavior as Dart before null-safety.
The point of null-safety is to prevent things that shouldn't be null from ever being null. You could have written such code before, but without null-safety, that meant performing runtime null checks (e.g. assert(x != null);, if (x != null) { ... }, or relying on a null-pointer-exception to crash the program if null was used where it wasn't expected). Null-safety means that such checks now can be done at build-time by static analysis, which means that errors can be caught earlier and more completely. Furthermore, whereas previously functions needed to explicitly document whether arguments and return values were allowed to be null (and inadequate or incorrect documentation could be a source of errors), now they're self-documenting in that regard. It's just like using int foo(String s) versus dynamic foo(dynamic s); using strong types catches errors earlier and better describes the function's contract.
I recommend reading Understanding Null Safety if you haven't already done so.
I would like to advice you to use the ! operator, also the called bang operator, as little as possible. You should only use this operator when the dart analyser is wrong and you know for 100% that the value will never be null.
Below is an example of where the dart analyser would be wrong and you should use the bang operator.
// We have a class dog with a nullable name.
class Dog {
String? name;
Dog({this.name});
}
void main() {
// We create a dog without a name.
final dog = Dog();
// We assign the dog a name.
dog.name = 'George';
// The dart analyser will show an error because it can't know if the
// name of the object is not null.
//
// Will throw: `A value of type 'String?' can't be assigned to a
// variable of type 'String'`.
String myDogsName = dog.name;
// To avoid this, you should use the bang operator because you `know` it
// is not null.
String myDogsName = dog.name!;
}
The ? operator simply tells Dart that the value can be null. So every time you want to place a ? operator, ask yourself, can this value ever be null?
The null safety features in Dart are mainly created for helping the developer remember when a value can be null. Dart will now simply tell you when you made a variable nullable in order to force null checks or default values for example.

How to check 'late' variable is initialized in Dart

In kotlin we can check if the 'late' type variables are initialized like below
lateinit var file: File
if (this::file.isInitialized) { ... }
Is it possible to do something similar to this in Dart..?
Unfortunately this is not possible.
From the docs:
AVOID late variables if you need to check whether they are initialized.
Dart offers no way to tell if a late variable has been initialized or
assigned to. If you access it, it either immediately runs the
initializer (if it has one) or throws an exception. Sometimes you have
some state that’s lazily initialized where late might be a good fit,
but you also need to be able to tell if the initialization has
happened yet.
Although you could detect initialization by storing the state in a
late variable and having a separate boolean field that tracks whether
the variable has been set, that’s redundant because Dart internally
maintains the initialized status of the late variable. Instead, it’s
usually clearer to make the variable non-late and nullable. Then you
can see if the variable has been initialized by checking for null.
Of course, if null is a valid initialized value for the variable, then
it probably does make sense to have a separate boolean field.
https://dart.dev/guides/language/effective-dart/usage#avoid-late-variables-if-you-need-to-check-whether-they-are-initialized
Some tips I came up with from advice of different dart maintainers, and my self-analysis:
late usage tips:
Do not use late modifier on variables if you are going to check them for initialization later.
Do not use late modifier for public-facing variables, only for private variables (prefixed with _). Responsibility of initialization should not be delegated to API users. EDIT: as Irhn mentioned, this rule makes sense for late final variables only with no initializer expression, they should not be public. Otherwise there are valid use cases for exposing late variables. Please see his descriptive comment!
Do make sure to initialize late variables in all constructors, exiting and emerging ones.
Do be cautious when initializing a late variable inside unreachable code scenarios. Examples:
late variable initialized in if clause but there's no initialization in else, and vice-versa.
Some control-flow short-circuit/early-exit preventing execution to reach the line where late variable is initialized.
Please point out any errors/additions to this.
Enjoy!
Sources:
eernstg's take
Hixie's take
lrhn's take
leafpetersen's final verdict as of 2021 10 22
Effective Dart
Self-analysis on how to approach this with some common-sense.
You can create a Late class and use extensions like below:
import 'dart:async';
import 'package:flutter/foundation.dart';
class Late<T> {
ValueNotifier<bool> _initialization = ValueNotifier(false);
late T _val;
Late([T? value]) {
if (value != null) {
this.val = value;
}
}
get isInitialized {
return _initialization.value;
}
T get val => _val;
set val(T val) => this
.._initialization.value = true
.._val = val;
}
extension LateExtension<T> on T {
Late<T> get late => Late<T>();
}
extension ExtLate on Late {
Future<bool> get wait {
Completer<bool> completer = Completer();
this._initialization.addListener(() async {
completer.complete(this._initialization.value);
});
return completer.future;
}
}
Create late variables with isInitialized property:
var lateString = "".late;
var lateInt = 0.late;
//or
Late<String> typedLateString = Late();
Late<int> typedLateInt = Late();
and use like this:
print(lateString.isInitialized)
print(lateString.val)
lateString.val = "initializing here";
Even you can wait for initialization with this class:
Late<String> lateVariable = Late();
lateTest() async {
if(!lateVariable.isInitialized) {
await lateVariable.wait;
}
//use lateVariable here, after initialization.
}
Someone may kill you if they encounter it down the road, but you can wrap it in a try/catch/finally to do the detection. I like it better than a separate boolean.
We have an instance where a widget is disposed if it fails to load and contains a late controller that populates on load. The dispose fails as the controller is null, but this is the only case where the controller can be null. We wrapped the dispose in a try catch to handle this case.
Use nullable instead of late:
File? file;
File myFile;
if (file == null) {
file = File();
}
myFile = file!;
Note the exclamation mark in myFile = file!; This converts File? to File.
I'm using boolean variable when I initiliaze late varible.
My case is :
I'm using audio player and I need streams in one dart file.
I'm sharing my code block this methodology easily implement with global boolean variables to projects.
My problem was the exception i got from dispose method when user open and close the page quickly