Created
October 27, 2020 06:17
-
-
Save chimon2000/c6d81a58ae71160bcc2d8128df1c03fe to your computer and use it in GitHub Desktop.
Command Pattern in Dart (binder)
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(this._context); | |
T locate<T>(LogicRef<T> ref) => _context.use(ref); | |
T read<T>(StateRef<T> ref) => _context.read(ref); | |
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 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)); |
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 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)); |
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(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; | |
} | |
} |
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 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