Dart / flutter test setup with null safety

3,201

Solution 1

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

Solution 2

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;

Share:
3,201
Admin
Author by

Admin

Updated on December 28, 2022

Comments

  • Admin
    Admin 10 months

    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);
        });
      });
    }