Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Command Pattern in Dart (binder)
abstract class BaseCommand<T> {
BuildContext _context;
T locate<T>(LogicRef<T> ref) => _context.use(ref);
T read<T>(StateRef<T> ref) =>;
Future<T> run();
class UserService with Logic {
Future<bool> login(String user, String pass) => Future.value(true);
final Scope scope;
final userServiceRef = LogicRef((scope) => UserService(scope));
class UserController with Logic {
const UserController(this.scope);
final Scope scope;
void updateUser(String user) => write(userStateRef, User(user));
final userControllerRef = LogicRef((scope) => UserController(scope));
class LoginCommand extends BaseCommand<bool> {
final String user;
final String pass;
LoginCommand(BuildContext context, {this.user, this.pass}) : super(context);
run() async {
UserService userService = locate(userServiceRef);
UserController userController = locate(userControllerRef);
// Await some service call
bool loginSuccess = await userService.login(user, pass);
// Update appModel with current user. Any views bound to this will rebuild
userController.updateUser(loginSuccess ? user : null);
// Return the result to whoever called us, in case they care
return loginSuccess;
class User {
final String user;
final userStateRef = StateRef<User>(null);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment