Skip to content

Instantly share code, notes, and snippets.

@mj-hd
Created March 31, 2022 11:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mj-hd/fbe79a46c183992e207db63b8e2e1912 to your computer and use it in GitHub Desktop.
Save mj-hd/fbe79a46c183992e207db63b8e2e1912 to your computer and use it in GitHub Desktop.
null safe controller
class FooController {
_State? _state;
bool get hasState => _state != null;
void _attach(_State state) {
_state = state;
}
void hello() {
_state!.hello();
}
String get value => _state!.value;
}
class SafeFooController {
_State? _state;
void _attach(_State state) {
_state = state;
}
void Function()? get hello {
return _state?.hello;
}
String? get value => _state?.value;
}
void main() {
final fooController = FooController();
final safeFooController = SafeFooController();
if (fooController.hasState) {
fooController.hello();
print(fooController.value);
} else {
print('empty');
}
safeFooController.hello?.call();
print(safeFooController.value ?? 'empty');
}
class _State {
final String value = 'hello';
void hello() {
print(value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment