Stacked-Org / stacked

A Flutter application architecture created from real world scenarios
MIT License
935 stars 256 forks source link

listenToFormUpdated dont execute _updateFormData(model) ? #355

Closed jossephalvarez closed 3 years ago

jossephalvarez commented 3 years ago

Hello guys! .

I'm trying to implement a login form using this tutorial: https://www.filledstacks.com/post/building-flutter-login-and-sign-up-forms/

I would like to print on viewModel, the username and password. Simple right?

But I allways obtaing null values:

I've debugged and I discover that never enter on : _updateFormData(model)); (Autogenerate code that generate : LoginView.form.dart)

My view is :

@FormView(fields: [
  FormTextField(name: 'username'),
  FormTextField(name: 'password', isPassword: true),
])
class LoginView extends StatelessWidget with $LoginView {
  LoginView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<LoginViewModel>.reactive(
      onModelReady: (model) => listenToFormUpdated(model),
      builder: (context, model, child) => Scaffold(
        body: AuthenticationLayout(
          busy: model.isBusy,
          validationMessage: model.validationMessage,
          onMainButtonTapped: model.doLogin,
          onCantAccessAccountTapped: model.navigateToFailedAccess,
          title: 'Bienvenido!',
          subtitle: 'Por favor, introduce tu nombre de usuario y contraseña',
          mainButtonTitle: 'ENTRAR',
          form: Column(
            children: [
              TextField(
                decoration: InputDecoration(labelText: 'Nombre de usuario'),
                controller: usernameController,
              ),
              TextField(
                decoration: InputDecoration(labelText: 'Contraseña'),
                controller: passwordController,
              ),
              verticalSpaceTiny,
              Row(
                children: [
                  Checkbox(
                    value: false,
                    onChanged: (bool? value) {},
                  ),
                  Text(
                    'Recordar contraseña',
                    style: TextStyle(color: kcMediumGreyColor, fontSize: 14),
                  ),
                ],
              )
            ],
          ),
        ),
      ),
      viewModelBuilder: () => LoginViewModel(),
    );
  }
}

And my viewModel is :

class LoginViewModel extends FormViewModel {
  final navigationService = locator<NavigationService>();

  void navigateToFailedAccess() =>
      navigationService.navigateTo(Routes.startupView);

  void doLogin() {
    print('....do login on viewModel');
    print('formValueMap on doLogin:$formValueMap');
    print('usernameValue on doLogin: $usernameValue');
    print('passwordValue on doLogin: $passwordValue');
    print('hasUsername on doLogin: $usernameValue');
    print('hasPassword on doLogin: $passwordValue');   
    //setValidationMessage('Usuario y/contraseña incorrectas.');
    notifyListeners();
  }

  @override
  void setFormStatus() {}
} 

And autogenerate class is :


import 'package:flutter/material.dart';
import 'package:stacked/stacked.dart';

const String UsernameValueKey = 'username';
const String PasswordValueKey = 'password';

mixin $LoginView on StatelessWidget {
  final TextEditingController usernameController = TextEditingController();
  final TextEditingController passwordController = TextEditingController();
  final FocusNode usernameFocusNode = FocusNode();
  final FocusNode passwordFocusNode = FocusNode();

  /// Registers a listener on every generated controller that calls [model.setData()]
  /// with the latest textController values
  void listenToFormUpdated(FormViewModel model) {
    usernameController.addListener(() => _updateFormData(model));
    passwordController.addListener(() => _updateFormData(model));
  }

  /// Updates the formData on the FormViewModel
  void _updateFormData(FormViewModel model) => model.setData(
        model.formValueMap
          ..addAll({
            UsernameValueKey: usernameController.text,
            PasswordValueKey: passwordController.text,
          }),
      );

  /// Calls dispose on all the generated controllers and focus nodes
  void disposeForm() {
    // The dispose function for a TextEditingController sets all listeners to null

    usernameController.dispose();
    passwordController.dispose();
  }
}

extension ValueProperties on FormViewModel {
  String? get usernameValue => this.formValueMap[UsernameValueKey];
  String? get passwordValue => this.formValueMap[PasswordValueKey];

  bool get hasUsername => this.formValueMap.containsKey(UsernameValueKey);
  bool get hasPassword => this.formValueMap.containsKey(PasswordValueKey);
}

extension Methods on FormViewModel {} 

I would like to print on my method doLogin of ViewModel because in it i'll connect with my remote service to connect with my backend.

On the other hand, I would like to do a questions about this point :

  1. How can i implement Remeber pass on form ? Should added this functionality on my view model ?

Thank you in advance ?

FilledStacks commented 3 years ago

Everything looks fine to me. Can you print out the values in setFormStatus and see what it shows?

  1. I would use secure preferences to save the data and fill it in again later
jossephalvarez commented 3 years ago

Hello @FilledStacks

I've tried some things :

  1. Add setFormStatus(); on my method doLogin, before to print the values , and it doesnt work
  2. on the override method setFormStatus of my viewModel, I've added the prints but i never see this outputs on my console.
  3. setFormStatus is a empty method(Im not sure if it should be empty), I've checked it on form_viewmodel.dart and the code is :
  4. I've write print on setData but it never appears on console:
import 'package:stacked/src/state_management/reactive_service_mixin.dart';

/// Provides functionality to reduce the code required in order to move user input
/// into the [ViewModel]
abstract class FormViewModel extends ReactiveViewModel {
  @override
  List<ReactiveServiceMixin> get reactiveServices => [];

  bool _showValidation = false;
  bool get showValidation => _showValidation;

  String? _validationMessage;
  String? get validationMessage => _validationMessage;

  /// Stores the mapping of the form key to the value entered by the user
  Map<String, dynamic> formValueMap = Map<String, dynamic>();

  void setValidationMessage(String? value) {
    _validationMessage = value;
    _showValidation = _validationMessage?.isNotEmpty ?? false;
  }

  void setData(Map<String, dynamic> data) {
    print('...on setData');
    // Save the data from the controllers
    formValueMap = data;

    // Reset the form status
    setValidationMessage(null);

    // Set the new form status
    setFormStatus();

    // Rebuild the UI
    notifyListeners();
  }

  /// Called after the [formValueMap] has been updated and allows you to set
  /// values relating to the forms status.
  void setFormStatus();
}

On My pubspec.yaml is :

description: A new Flutter project.

# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  stacked: ^2.1.0
  stacked_services:
  get_it: ^6.1.1
  http: ^0.13.1
  device_preview: ^0.7.1
  lint: ^1.0.0

dev_dependencies:
  flutter_test:
    sdk: flutter
  build_runner:
  stacked_generator: ^0.4.1
  flutter_native_splash: ^1.1.8+4

flutter_native_splash:
  color: '#ffffff'
  color_dark: '#7d7d7d'
  image: assets/splash.png
  image_dark: assets/splash.png
  android : true
  ios: true

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # assets:
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg
  assets:
    - assets/images/

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages
jossephalvarez commented 3 years ago

SOLVED!

The solution is :

  1. Remove pubspec.lock
  2. Excecute: flutter pub get && flutter clean
  3. Use _devicepreview package only for debug mode(to check how looks the view) -> I have been testing my app using device_preview and I dont know why it doesnt work with forms. I've comment it and now it works perfect!

    void main() async {
    await initializeDI();
    setupLocator();
    // PROD MODE
    runApp(MyApp());
    
    // DEBUG MODE
    /*  runApp(
    DevicePreview(
      enabled: !kReleaseMode,
      builder: (context) => MyApp(), // Wrap your app
    ),
    );*/
    }
saileshbro commented 2 years ago

@FilledStacks I am also facing this issue. I have used this before but suddenly it's giving this issue.

Purvesh-Modi commented 2 years ago

@FilledStacks I am also facing the same issue. I am using stacked: ^2.2.2 version as my dependency. Couple of weeks ago it was working as expected.

Can you please help me out?

JaidynBluesky commented 2 years ago

@saileshbro Removing pubspec.lock and running flutter clean && flutter pub get should work. I'm not sure why we need to to do this, it's happening to me too.