Created
March 31, 2022 11:05
-
-
Save mj-hd/fbe79a46c183992e207db63b8e2e1912 to your computer and use it in GitHub Desktop.
null safe controller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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