Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Command Pattern in Dart (Cubit + GetIt)
import 'package:get_it/get_it.dart';
abstract class BaseCommand<T> {
GetIt getIt = GetIt.instance;
D locate<D>() => getIt.get<D>();
Future<T> run();
class LoginCommand extends BaseCommand<bool> {
final String user;
final String pass;
LoginCommand({this.user, this.pass});
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;
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