Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart / flutter test setup with null safety

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);
    });
  });
}
like image 752
Jeff Bailey Avatar asked Mar 12 '21 02:03

Jeff Bailey


People also ask

How do you assign a null value in Dart?

With sound null safety variables are 'non-nullable' by default: They can be assigned only values of the declared type (e.g. int i=42 ), and never be assigned null . You can specify that a type of a variable is nullable (e.g. int? i ), and only then can they contain either a null or a value of the defined type.

How do you avoid null safety error in Flutter?

Copy: --no-sound-null-safety and add into "additional run args". Run your app with "Run/Play" Button or from "Run" Menu. In this way, you can solve "Error: Cannot run with sound null safety, because the following dependencies don't support null safety" error on Flutter project.


2 Answers

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

like image 115
nukotsuka Avatar answered Nov 05 '22 14:11

nukotsuka


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;

like image 34
Eishon Avatar answered Nov 05 '22 14:11

Eishon