In this section, the target

  • What does air safety mean
  • How to migrate code
  • How do I disable air security
  • Code specification examples

video

www.bilibili.com/video/bv1g5…

code

Github.com/ducafecat/g…

reference

  • dart.cn/null-safety
  • The dart. Cn/null – safety…
  • The dart. Cn/null – safety…
  • The dart. Cn/null – safety…
  • The dart. Cn/null – safety…

The body of the

What does air safety mean

  • Default non-null
String title = 'ducafecat';
Copy the code
  • type?The operator
String? title = null;
Copy the code
  • value!The operator
String? title = 'ducafecat';
StringnewTitle = title! ;Copy the code
  • value?The operator
String? title = 'ducafecat';
boolisEmpty = title? .isEmpty();Copy the code
  • value??The operator
String? title = 'ducafecat';
String newTitle = title ?? 'cat';
Copy the code
  • lateThis is checked at run time. So use it only if you are sure it will be initialized before it is used
late String? title;
title = 'ducafecat';
Copy the code
  • The List, the generic
type Whether the set is nullable Whether the data item is nullable
List no no
List? yes no
List<String? > no yes
List<String? >? yes yes
  • Map
type Whether the set is nullable Whether the data item is nullable
Map<String, int> no no*
Map<String, int>? yes no*
Map<String, int? > no yes
Map<String, int? >? yes yes

* May return null

// It is possible to return null
int value = <String.int> {'one': 1} ['one']; // ERROR

// Need to add type?
int? value = <String.int> {'one': 1} ['one']; // OK

/ / or the value!
int value = <String.int> {'one': 1} ['one']! ;// OK

Copy the code

Benefits brought about

  • Healthier code
  • Good user experience
  • Run faster
  • Compiled files are smaller

Enable and migrate

  • pubspec.yaml
Environment: the SDK: "> = 2.12.0 < 3.0.0"Copy the code
  • Transfer order

We strongly recommend that you migrate your code sequentially, starting with the dependencies at the bottom of the dependency relationship. For example, if C depends on B and B depends on A, the migration should be in the order of A -> B -> C.

  • Checking dependencies
Dart --version > Dart --version > Dart pub outdated --mode=null-safetyCopy the code
  • Upgrade depend on
Dart pub upgrade --null-safety dart pub upgradeCopy the code
  • The migration tool
> dart migrate
Copy the code
  • Analysis of the
> dart analyze
Copy the code

Disable air safety

  • Cli command
> dart --no-sound-null-safety run
> flutter run --no-sound-null-safety
Copy the code
  • .vscode/launch.json
{
  // Use IntelliSense to learn about related attributes.
  // Hover to view descriptions of existing properties.
  / / for more information, please visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0"."configurations": [{"name": "getx_quick_start"."request": "launch"."type": "dart"."program": "lib/main.dart"."args": ["--no-sound-null-safety"]]}}Copy the code

Examples, specifications

The dart. Cn/null – safety…

  • Explicitly handle empty state
makeCoffee(String coffee, [String? dairy]) {
  if(dairy ! =null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee'); }}Copy the code
  • ** Top-level variables and static fields must contain an initialization method. ** Since they can be accessed from anywhere in the program, the compiler cannot guarantee that they are assigned values before they are used. The only safe option is to require that the initialization expression itself be included to ensure that a value of the matching type is produced.
int topLevel = 0;

class SomeClass {
  static int staticField = 0;
}
Copy the code
  • The fields of an instance must also include an initialization method when declared, either in the usual initialization form or in the constructor of the instance.
class SomeClass {
  int atDeclaration = 0;
  int initializingFormal;
  int initializationList;

  SomeClass(this.initializingFormal)
      : initializationList = 0;
}
Copy the code
  • Local variables are the most flexible. A non-empty variable does not necessarily require an initialization method.
int tracingFibonacci(int n) {
  int result;
  if (n < 2) {
    result = n;
  } else {
    result = tracingFibonacci(n - 2) + tracingFibonacci(n - 1);
  }

  print(result);
  return result;
}
Copy the code
  • Process analysis, where Dart willobjectThe type declared from itObjecttoList. The following program cannot run until air safety is introduced.
// With (or without) null safety:
bool isEmptyList(Object object) {
  if (object is List) {
    return object.isEmpty; // <-- OK!
  } else {
    return false;
  }
}

->

// Without null safety:
bool isEmptyList(Object object) {
  if (object is! List) return false;
  return object.isEmpty;
}
Copy the code
  • Absolute assignment analysis
int tracingFibonacci(int n) {
  final int result;
  if (n < 2) {
    result = n;
  } else {
    result = tracingFibonacci(n - 2) + tracingFibonacci(n - 1);
  }

  print(result);
  return result;
}
Copy the code
  • Warning of useless code
String checkList(List list) {
  if(list? .isEmpty) {return 'Got nothing';
  }
  return 'Got something';
}
Copy the code
  • Lazy-loaded variables,lateThe modifier is “constrain variables at run time, not compile time.” This makeslateThis term is approximately equal towhenEnforce constraints on variables.
// Using null safety:
class Coffee {
  String? _temperature;

  void heat() { _temperature = 'hot'; }
  void chill() { _temperature = 'iced'; }

  String serve() => _temperature! + ' coffee'; } - >// Using null safety:
class Coffee {
  late String _temperature;

  void heat() { _temperature = 'hot'; }
  void chill() { _temperature = 'iced'; }

  String serve() => _temperature + ' coffee';
}

Copy the code
  • latefinalUsed in combination with ordinaryfinalUnlike fields, you do not need to initialize them at declaration or construction time. You can load it later somewhere in the run. But you can only do itAt a timeAssigns a value, and it validates at run time.
// Using null safety:
class Coffee {
  late final String _temperature;

  void heat() { _temperature = 'hot'; }
  void chill() { _temperature = 'iced'; }

  String serve() => _temperature + ' coffee';
}
Copy the code
  • All parameters here must be passed by name. parameteracIs optional and can be omitted. parameterbdIs required and must be passed when called. Note here that being required is independent of being nullable.
// Using null safety:
function({int? a, required int? b, int? c, required int? d}) {}
Copy the code
  • Abstract field
abstract class Cup {
  Beverage get contents;
  setcontents(Beverage); } - >abstract class Cup {
  abstract Beverage contents;
}

Copy the code
  • Some assignment calculations can be moved to static initializations.
// Initalized without values
ListQueue _context;
Float32List _buffer;
dynamic _readObject;

Vec2D(Map<String.dynamic> object) {
  _buffer = Float32List.fromList([0.0.0.0]);
  _readObject = object['container'];
  _context = ListQueue<dynamic> (); } - >// Initalized with values
final ListQueue _context = ListQueue<dynamic> ();final Float32List _buffer = Float32List.fromList([0.0.0.0]);
final dynamic _readObject;

Vec2D(Map<String.dynamic> object) : _readObject = object['container'];


Copy the code
  • May returnnullFactory method of
factory StreamReader(dynamic data) {
  StreamReader reader;
  if (data is ByteData) {
    reader = BlockReader(data);
  } else if (data is Map) {
    reader = JSONBlockReader(data);
  }
  returnreader; } - >factory StreamReader(dynamic data) {
  if (data is ByteData) {
    // Move the readIndex forward for the binary reader.
    return BlockReader(data);
  } else if (data is Map) {
    return JSONBlockReader(data);
  } else {
    throw ArgumentError('Unexpected type for data'); }}Copy the code

The elder brother of the © cat

This video document

Ducafecat. Tech / 2021/04/09 /…

GetX Quick Start code

Github.com/ducafecat/g…

News client code

Github.com/ducafecat/f…

Strapi manual translation

getstrapi.cn

Wechat discussion group Ducafecat

The period of video

  • Dart programming language basics

Space.bilibili.com/404904528/c…

  • Start Flutter with zero basics

Space.bilibili.com/404904528/c…

  • Flutter combat news client from scratch

Space.bilibili.com/404904528/c…

  • Flutter component development

Space.bilibili.com/404904528/c…

  • Flutter component development

Space.bilibili.com/404904528/c…

  • Flutter Bloc

Space.bilibili.com/404904528/c…

  • Flutter Getx4

Space.bilibili.com/404904528/c…

  • Docker Yapi

Space.bilibili.com/404904528/c…