Skip to content

Instantly share code, notes, and snippets.

@chimon2000
Last active July 30, 2021 14:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chimon2000/697a41a30da74ecce1abf541dabc132c to your computer and use it in GitHub Desktop.
Save chimon2000/697a41a30da74ecce1abf541dabc132c to your computer and use it in GitHub Desktop.
Command Pattern in Dart
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();
}
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;
}
}
class UserCubit extends Cubit<User> {
UserCubit() : super(null);
void update(String user) => emit(User(user));
}
class User {
final String user;
User(this.user);
}
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