Created
June 7, 2020 15:54
-
-
Save lukepighetti/5992def9291939e3d0a6cb0686516538 to your computer and use it in GitHub Desktop.
Why does initState/dispose need to have a super call when they could be called by an internal method instead?
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
/// Alternative architecture for Flutter lifecycle methods. | |
/// | |
/// Currently the framework uses @mustCallSuper to ensure that | |
/// important operations are called when lifecycle methods are | |
/// overridden. However, it is a common source of confusion for | |
/// developers about if the super should be called before or after | |
/// their own code. | |
/// | |
/// This is a proposed alternative which has an internal `handleLifecycleMethod()` | |
/// method for each lifecycle event which calls `lifecycleMethod()` in the appropriate | |
/// order among the other internal code. | |
/// | |
/// In short: | |
/// - Removes the need for @mustCallSuper | |
/// - Ensures that framework code is called in the correct order | |
main() async { | |
var foo = MyWidgetState(); | |
foo.handleInitState(); | |
foo.handleDispose(); | |
} | |
class MyWidgetState extends WidgetState { | |
@override | |
initState(){ | |
/// No super, internal order of operations preserved | |
print("initState()"); | |
} | |
@override | |
dispose(){ | |
/// No super, internal order of operations preserved | |
print("dispose()"); | |
} | |
} | |
class WidgetState { | |
/// Override this lifecycle method | |
void initState(){} | |
/// Framework uses this internally | |
void handleInitState(){ | |
initState(); | |
print("Do a thing always after initState()"); | |
} | |
/// Override this lifecycle method | |
void dispose(){} | |
/// Framework uses this internally | |
void handleDispose(){ | |
print("Do a thing always before dispose()"); | |
dispose(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment