Last active
July 30, 2021 14:41
-
-
Save chimon2000/697a41a30da74ecce1abf541dabc132c to your computer and use it in GitHub Desktop.
Command Pattern in Dart
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
abstract class BaseCommand<T> { | |
BuildContext _context; | |
BaseCommand(BuildContext context) { | |
/// Get root context | |
/// If we're passed a context that is known to be root, skip the lookup, it will throw an error otherwise. | |
_context = (context == _lastKnownRoot) ? context : context.read(); | |
_lastKnownRoot = _context; | |
} | |
T locate<T>() => _context.read(); | |
static BuildContext _lastKnownRoot; | |
Future<T> run(); | |
} |
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 LoginCommand extends BaseCommand<bool> { | |
final String user; | |
final String pass; | |
LoginCommand(BuildContext context, {this.user, this.pass}) : super(context); | |
@override | |
run() async { | |
UserService userService = locate(); | |
UserCubit userBloc = locate(); | |
// Await some service call | |
bool loginSuccess = await userService.login(user, pass); | |
// Update appModel with current user. Any views bound to this will rebuild | |
userBloc.update(loginSuccess ? user : null); | |
// Return the result to whoever called us, in case they care | |
return loginSuccess; | |
} | |
} |
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 UserCubit extends Cubit<User> { | |
UserCubit() : super(null); | |
void update(String user) => emit(User(user)); | |
} | |
class User { | |
final String user; | |
User(this.user); | |
} |
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 UserService { | |
Future<bool> login(String user, String pass) => Future.value(true); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment