简体   繁体   中英

How can I use riverpod's statenotifier for handling a form?

I'm trying to use StateNotifier to handle a form but watching the stateNotifierProvider, I get the object I'm trying to update instead of the provider.

Here is my implementation:

final profileCreationFormNotifierProvider =
    StateNotifierProvider((ref) => ProfileCreationFormNotifier());

class ProfileCreationFormNotifier extends StateNotifier<ProfileModel> {
  ProfileCreationFormNotifier()
      : super(
          ProfileModel(
            city: '',
            country: '',
            firstname: '',
            lastname: '',
            pictureUrl: '',
            username: '',
            gender: '',
          ),
        );

  void setFirstname(String firstname) {
    state = state.copyWith(firstname: firstname);
  }

  void setLatstname(String lastname) {
    state.copyWith(lastname: lastname);
  }

  void setUsername(String username) {
    state.copyWith(username: username);
  }

  void setGender(String gender) {
    state.copyWith(gender: gender);
  }
}

Then in a Consumer widget I try to call the methods to update a field on the form like this

Consumer(
  builder:
      (BuildContext context, ScopedReader watch, Widget? child) {
    return CustomTextField(
      controller: usernameFieldController,
      hintText: 'Username',
      isEmail: false,
      onSave: (value) {
        context
            .read(profileCreationFormNotifierProvider)
            .setUsername(value);
      },
      onValidate: (value) => validator(value!, "Username"),
      secured: false,
    );
  },
),

I get the following error:

Class 'ProfileModel' has no instance method 'setUsername'. Receiver: Instance of 'ProfileModel' Tried calling: setUsername("qsqsqsq")

What I'm I doing wrong here?

I'm using hook_riverpod version: "0.14.0+2" Thank you for your help

As of Riverpod 0.14.0, State is the default value exposed by StateNotifierProvider.

Change:

context
  .read(profileCreationFormNotifierProvider)
  .setUsername(value);

to:

context
  .read(profileCreationFormNotifierProvider.notifier)
  .setUsername(value);

Similar question here .

More on the changes here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM