Skip to content

Instantly share code, notes, and snippets.

@chimon2000
Created October 27, 2020 06:17
Show Gist options
  • Save chimon2000/c6d81a58ae71160bcc2d8128df1c03fe to your computer and use it in GitHub Desktop.
Save chimon2000/c6d81a58ae71160bcc2d8128df1c03fe to your computer and use it in GitHub Desktop.
Command Pattern in Dart (binder)
abstract class BaseCommand<T> {
BuildContext _context;
BaseCommand(this._context);
T locate<T>(LogicRef<T> ref) => _context.use(ref);
T read<T>(StateRef<T> ref) => _context.read(ref);
Future<T> run();
}
class UserService with Logic {
UserService(this.scope);
Future<bool> login(String user, String pass) => Future.value(true);
@override
final Scope scope;
}
final userServiceRef = LogicRef((scope) => UserService(scope));
class UserController with Logic {
const UserController(this.scope);
@override
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);
@override
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;
User(this.user);
}
final userStateRef = StateRef<User>(null);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment