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