Created
October 22, 2020 00:54
-
-
Save chimon2000/4f358600f885ba877027abef0948e12f to your computer and use it in GitHub Desktop.
Command Pattern in Dart (Cubit + GetIt)
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
import 'package:get_it/get_it.dart'; | |
abstract class BaseCommand<T> { | |
GetIt getIt = GetIt.instance; | |
D locate<D>() => getIt.get<D>(); | |
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 LoginCommand extends BaseCommand<bool> { | |
final String user; | |
final String pass; | |
LoginCommand({this.user, this.pass}); | |
@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; | |
} | |
} |
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 UserCubit extends Cubit<User> { | |
UserCubit() : super(null); | |
void update(String user) => emit(User(user)); | |
} | |
class User { | |
final String user; | |
User(this.user); | |
} |
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 { | |
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