Skip to content

Instantly share code, notes, and snippets.

@lukepighetti
Created June 7, 2020 15:54
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 lukepighetti/5992def9291939e3d0a6cb0686516538 to your computer and use it in GitHub Desktop.
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?
/// 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