flutter_vm

Last updated:

0 purchases

flutter_vm Image
flutter_vm Images
Add to Cart

Description:

flutter vm

ViewModel Library #
A Flutter ViewModel implementation. Use Mixin for use in Stateful Widget or sample constructor for use in Stateless.
In your CustomViewModel you can use UseCase or custom Future.
You can listen to your stream in your Widget or use SnapshotBuilder in your build method.
You can see a full example at this repo.
Flutter ViewModel Example
ViewModel #
class AuthViewModel extends BaseViewModel {

final LogoutUseCase _logoutUseCase = LoginUseCase();



//you can listen this in your UI
final isUserLogged = BroadcastStream<bool>();

void login() {
executeUseCase(_loginUseCase, LoginParams("username", "password"),
broadcastStream: isUserLogged);
}


}
copied to clipboard
UseCase #
class LoginUseCase extends UseCase<LoginParams, bool>{
final UserRepository _userRepository;

LoginUseCase(this._userRepository);


@override
Future<bool> execute(LoginParams params)async {
await _userRepository.login();
return _userRepository.getIfUserIsLogged();
}

}

class LoginParams {
final String _username;
final String _password;

LoginParams(this._username, this._password);
}
copied to clipboard
Init in StateFul Widget #
class _LoginMixinWidgetState extends State<LoginMixinWidget>
with ViewModel<LoginMixinWidget, AuthViewModel> { //use mixin


@override
AuthViewModel getViewModel() => AuthViewModel(); // need constructor

@override
void initState() {
super.initState();
// now you can access to ViewModel with vm
vm.getIfUserIsLogged();
}

copied to clipboard
Init in StateLess Widget #
class _LoginWidgetState extends State<LoginWidget> {
AuthViewModel _authViewModel = AuthViewModel(); //basic init

@override
void initState() {
_authViewModel.getIfUserIsLogged();

super.initState();
}

@override
void dispose() {
_authViewModel.dispose();// you need to dispose
super.dispose();
}
copied to clipboard
Use SnapshotBuilder #
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: SnapshotBuilder<bool>(//need to specify data type
initialData: false,
broadcast: _authViewModel.isUserLogged, //broadcast in viu model you listen
onLoading: Container(),
onError: (e) {
//here you have error
return Container();
},
onData: (value) {
//here you have data
return Container();
},
),
),
);
}

copied to clipboard
Listen to a Stream #
int _counter = 0;

@override
void initState() {
vm.number.stream?.listen((value) {
setState(() {
_counter = value;
});
});

super.initState();
}

copied to clipboard

License:

For personal and professional use. You cannot resell or redistribute these repositories in their original state.

Files In This Product:

Customer Reviews

There are no reviews.